2015-12-08 42 views
0

比方说,为简单起见,我有三大类:的Django/Postgres的:显示不同的多对多项目

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包含列表1和项目list3。

List1包含Item1,Item2,Item3。

List2包含Item1,Item2和Item4。

List3只包含Item3。

我想返回所有属于BigThing1,省略重复,像这样的项目:

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) 

我觉得有涉及prefetch_related或select_related东西,但也有点为难,因为我新的Django/Postgres。在过去,我会做一个JOIN查询,但承认这些查询无论如何都是黑客,无论如何,我想知道这种查询的最佳做法。

回答