tags:

views:

153

answers:

2

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...

+4  A: 

You almost got it right...

ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct()
Yuval A
A: 

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.

Grant