查询跨越并跟随几个表

问题描述 投票:0回答:1

我的问题是创建一个查询,过滤通过几个中间表相关的对象。我的关系数据库看起来像这样:

enter image description here

一个用户可以上传任意数量的产品(一对多关系)。但是,用户也可以对产品进行排名。排名可以由几个用户完成,并且用户可以具有多个排名(多对多关系)。产品和排名之间也是如此。我使用显式中间表(Rank和Belong),它通过through参数定义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,Ranking和Rank表之间的“跟随”关系。我在Django tutorial之后尝试了这个,但它不起作用:

Product.objects.filter(belong__ranking__rank__user=”username”)
django django-queryset django-orm
1个回答
1
投票

你的M2M关系和他们的模型之间有点混淆。

例如,我不明白为什么从产品到排名的M2M被称为“属于”。它应该被称为“排名”。您从排名到用户的M2M至少具有正确的基本名称,但它指向许多用户,因此应该是“用户”。

然而,重点是当您遵循M2M时,您不需要考虑直通表。另一个问题是“用户”本身就是一个模型,因此要与用户名进行比较,您需要继续关注该字段。所以:

Product.objects.filter(belong__user__username="username")
© www.soinside.com 2019 - 2024. All rights reserved.