Django QuerySet ordering by number of reverse ForeignKey matches

Posted by msanders on Stack Overflow See other posts from Stack Overflow or by msanders
Published on 2010-03-16T11:14:01Z Indexed on 2010/03/16 11:16 UTC
Read the original article Hit count: 604

Filed under:
|

I have the following Django models:

class Foo(models.Model):
    title = models.CharField(_(u'Title'), max_length=600)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    eg_id = models.PositiveIntegerField(_(u'Example ID'), default=0)

I wish to return a list of Foo objects which have a reverse relationship with Bar objects that have a eg_id value contained in a list of values. So I have:

id_list = [7, 8, 9, 10]
qs = Foo.objects.filter(bar__eg_id__in=id_list)

How do I order the matching Foo objects according to the number of related Bar objects which have an eg_id value in the id_list?

© Stack Overflow or respective owner

Related posts about django

Related posts about python