On Sat, Jul 3, 2010 at 7:20 PM, Wiiboy <jordon...@gmail.com> wrote: > Is there a way to filter based on the result of a model instance > method? > > I've got a Permission model with a one-to-one relationship with an > Article. The Permission model stores the different groups that the > Article author said could read their article. There's about 6 groups > though, so I wrote an instance method that calculates whether a given > user can view an Article. > > I want to filter based on whether that instance method returns true or > not. I could do something like the following, but it seems very > inefficient. >
As other have already written, it's not possible to filter on the result of a model method. There's at least one thing you can do differently to speed up this method a bit. > def myview(request): > q = Article.objects.all() > for item in q: > if not item.permission.can_view_article(request.user): > q = q.exclude(item.pk) > Everytime you call exclude (btw, this should be q = q.exclude(pk=item.pk), no?), a new queryset instance is constructed. This is probably not neccessary. You could do this instead, assuming permission is another database model linked with a foreign key: articles = [article for article in Article.objects.all().select_related('permission') if article.permission.can_view_article(request.user)] At least you'll hit the article table only once this way. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.