查询哪个跨越并返回几个表

时间:2018-09-13 11:37:36

标签: django django-queryset django-orm

我的问题是关于创建一个查询,该查询过滤通过多个中间表相关的对象。我的关系数据库如下所示:

enter image description here

一个用户可以上传任意数量的产品(一对多关系)。但是,用户也可以对产品进行排名。排名可以由多个用户完成,一个用户可以具有多个排名(多对多关系)。产品和排名之间也是如此。我使用显式中间表(Rank和Belong),它们通过直通参数定义M2M关系,因为它们具有描述该关系的附加信息。

模型代码是这样的(为简单起见,我省略了无关的字段):

class Product(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    belong= models.ManyToManyField(Ranking, through="Belong")
    #...

#The M2M table which relates Product and Ranking
class Belong(models.Model):
    ranking = models.ForeignKey(Ranking, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    #...
    class Meta:
        unique_together = (("ranking", "product"))

class Ranking(models.Model):
    user= models.ManyToManyField(settings.AUTH_USER_MODEL, through="Rank")
    created = models.DateTimeField(auto_now_add=True)
    #...

#The M2M table which relates User and Ranking
class Rank(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ranking = models.ForeignKey(Ranking, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    #...
    class Meta:
        unique_together = (("user", "ranking"))

#The AUTH_USER_MODEL, which is not included here

我的问题是:如何创建一个查询来过滤给定用户排名的产品的查询?这意味着在Belong,Rank和Rank表之间存在“跟进”关系。我在Django tutorial之后尝试了此操作,但没有成功:

Product.objects.filter(belong__ranking__rank__user=”username”)

0 个答案:

没有答案