Reputation: 1524
Let's say for the sake of simplicity that I have three classes:
class BigThing(models.Model):
title = models.CharField(max_length=48)
stufflists = models.ManyToManyField(StuffList)
class StuffList(models.Model):
title = models.CharField(max_length=48)
stuff = models.ManyToManyField(Stuff)
class Stuff(models.Model):
code = models.CharField(max_length=24)
title = models.CharField(max_length=48)
description = RedactorField(blank=True, null=True)
BigThing1 contains List1 and List3.
List1 contains Item1, Item2, Item3 in it.
List2 contains Item1, Item2, and Item4.
List3 contains only Item3.
I would like to return all of the Items that belong to BigThing1, omitting duplicates, like so:
Item1, Item2, Item3
NOT: Item1, Item2, Item3, Item3
(and obviously not Item4, since that doesn't belong to either of the lists associated with BigThing1)
I feel like there's something involving prefetch_related or select_related, but am kind of stumped because I'm new to Django/Postgres. In the past I would have done a JOIN query, but acknowledge that those queries are kind of hacks anyway, and would like to know the best practice for this kind of query, anyway.
Upvotes: 0
Views: 59
Reputation: 32244
ManyToMany relationships can be followed backwards (specifically the section that starts "Reverse m2m queries are supported")
Something like the following should work
Stuff.objects.filter(stufflist__bigthing=BigThing1).distinct()
Upvotes: 1