pkdkk
pkdkk

Reputation: 3961

Django model filter with field_set, keep as queryset

I have a filter to list method that works, and can be used, but when i try to make and order_by on the list, in can't be done.

How can i do this and keep the queryset to make a order_by after the filter is applied,

I don't know of there is a better way to work with field_set's ?

models:

class Case(models.Model):
    user = models.ForeignKey(User)
    ....

class Share(models.Model):
    case = models.ForeignKey(Case)
    ....

class Field(models.Model):
    case = models.ForeignKey(Case)
    field = models.ForeignKey(DefaultField)
    ....

-

object_list = Field.objects.all()

l = [f for f in object_list if f.case.share_set.filter(user=request.user).count()]

Upvotes: 0

Views: 280

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

This is a very inefficient thing to do in any case. You should always try and do the filtering in the database as much as possible. Your query means that the db has to send all Field rows to Django, instantiate them, then throw away the ones that don't match. Instead you should just query for the ones you want:

object_list = Field.objects.filter(case__share__user=request.user)

Now, as well as being much more efficient, you have a queryset on which you can call order_by.

Upvotes: 2

Related Questions