DanielB
DanielB

Reputation: 2958

Getting FK set from given QuerySet

Using django, I'm trying to get a QuerySet of FK relationships from another QuerySet.

That is, given a relation like so: ParentTable (ParentID) and ChildTable(ChildID, ParentID

I have a particular QuerySet children = Child.objects.filter(**some_filters) and I need a QuerySet for the Parent objects "referenced" in the children QuerySet.

My initial thought was to use only, like so: Parent.objects.filter(id__in=child.only('parent')), but inspecting the SQL query shows that gives a WHERE clause along the lines of ParentID IN (SELECT subq.ChildID FROM ... which obviously yields undesired results. (inspection of the only method shows my use here is incorrect, so this behaviour is expected)

The desired query would be something ParentID IN (SELECT subq.ParentID FROM ...

Upvotes: 0

Views: 68

Answers (1)

Raunak Agarwal
Raunak Agarwal

Reputation: 7228

Well you have answered your question:

Consider this, when create a Foreign Key reference then, Django automatically creates a reverse reference for you which is why you are able to filter results based on the child. Moreover, if you want to abide this behavior you can use Symmetrical=False kwargs in the Model Field to not generate the reverse relationship.

class Parent(models.Model):
...

class Child(models.Model):
     parent = models.ForeignKey(Parent)

You can always make the query:

Parent.objects.filter(child__in = Childrens.objects.all())

Upvotes: 1

Related Questions