我有两个模型指定用于跟踪哪些用户已upvoted文章实例(在另一个应用程序,在这种情况下,articlescraper
)。ManyRelatedManager调用返回空列表时,它应该返回至少一个结果
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
articles_upvoted = models.ManyToManyField('useraccounts.UpvotedArticle',
null=True,
blank=True)
class UpvotedArticle(models.Model):
article = models.ForeignKey('articlescraper.Article')
user = models.ForeignKey(User)
在Django的壳,我试着用UserProfile
互动的方式获取的文章列表:
a = UserProfile.objects.get(pk=1)
a.articles_upvoted.all()
将返回:
[]
然而,那我走了稍微进一步:
b = UpvotedArticle.objects.filter(user=User.objects.get(pk=1))
b
将返回:
[<UpvotedArticle: Arch Linux Lexmark S305 Drivers>, <UpvotedArticle: Structure of a Haystack project>]
这是预期的行为,并反映在Django管理两个UserProfile
和UpvotedArticle
类别。
但是,我不明白,为什么试图获取文章列表不能按照我最初尝试使用a.articles_upvoted.all()
的方式完成,如果两个模型链接。