Tuesday, May 3, 2011

How to query filter in django without multiple occurrences

I have 2 models:

ParentModel: 'just' sits there

ChildModel: has a foreign key to ParentModel

ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()) gives multiple occurrences of ParentModel.

How do I query all ParentModels that have at least one ChildModel that's referring to it? And without multiple occurrences...

From stackoverflow
  • You almost got it right...

    ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct()
    
  • You might want to avoid using childmodel__in=ChildModel.objects.all() if the number of ChildModel objects is large. This will generate SQL with all ChildModel id's enumerated in a list, possibly creating a huge SQL query.

    If you can use Django 1.1 with aggregation support, you could do something like:

    ParentModel.objects.annotate(num_children=Count('child')).filter(num_children__gte=1)
    

    which should generate better SQL.

0 comments:

Post a Comment