views:

74

answers:

2

Hi!

Please regard the following Django models:


ParentModel(models.Model):
    ...

ChildModel(models.Model):
    parent = models.ForeignKey(ParentModel, related_name='children')

Let's assume there is certain subset of all children in the database available as a queryset (call it the 1st set).
Now, I'd like to gain access to the subset of all parents (call it the 2nd set) that said children from the 1st set relate to.

How do you do that without looping through the 1st set at the python level (and potentially cause a linear number of DB hits), i.e., with only one or two DB hits?

Thank you!

+4  A: 

Assuming you have a queryset called children:

ParentModel.objects.filter(children__in=children)
Daniel Roseman
A: 

Thanks - this worked!!

Supset