Django ManyRelatedManager调用在应返回至少一个结果时返回空列表
我有两个模型用于跟踪用户对文章实例的投票结果(在另一个应用程序中,在本例中为Django ManyRelatedManager调用在应返回至少一个结果时返回空列表,django,django-models,Django,Django Models,我有两个模型用于跟踪用户对文章实例的投票结果(在另一个应用程序中,在本例中为articlesrapper) 在Django shell中,我试图通过与UserProfile交互来获取文章列表: a = UserProfile.objects.get(pk=1) a.articles_upvoted.all() article_upvoted = models.ManyToManyField(articlescraper.Article, null=True,
articlesrapper
)
在Django shell中,我试图通过与UserProfile
交互来获取文章列表:
a = UserProfile.objects.get(pk=1)
a.articles_upvoted.all()
article_upvoted = models.ManyToManyField(articlescraper.Article, null=True,
blank=True, through=UpvotedArticle)
返回:
[]
[<UpvotedArticle: Arch Linux Lexmark S305 Drivers>, <UpvotedArticle: Structure of a Haystack project>]
然而,随后我又进一步指出:
b = UpvotedArticle.objects.filter(user=User.objects.get(pk=1))
b
返回:
[]
[<UpvotedArticle: Arch Linux Lexmark S305 Drivers>, <UpvotedArticle: Structure of a Haystack project>]
[,]
这是预期的行为,并且在Django admin的UserProfile
和UpvotedArticle
类别中都有反映
但是,我不明白,如果这两个模型是链接的,为什么不能像我最初尝试的那样使用
a.articles\u upvoted.all()
。,因为它们的关系不同。通过在一侧定义一个ForeignKey,在另一侧定义多个,您为数据库提供了两个单独的位置来存储有关投票的信息
您应该删除UserProfile
上的ManyToManyField
,只需使用自动反向关系:
a = UserProfile.objects.get(pk=1)
a.upvotedarticle_set.all()
或者,您可以将UpvotedArticle
识别为多个关系的“通过”表,并在articles\u upvoted
的定义中明确标记它-注意,该关系应与articlescraper.Article
,而不是UpvotedArticle
:
a = UserProfile.objects.get(pk=1)
a.articles_upvoted.all()
article_upvoted = models.ManyToManyField(articlescraper.Article, null=True,
blank=True, through=UpvotedArticle)
尽管由于没有在该关系上添加任何额外数据(这是定义显式直通表的通常原因),您可能希望完全删除它,而只依赖Django将创建的自动表