我指定了两个模型来跟踪用户对文章实例的支持(在另一个应用程序中,在这种情况下articlescraper
)。
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 shell 中,我尝试通过交互来获取文章列表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()
但是,我不明白,如果两个模型链接在一起,为什么不能按照我最初尝试使用的方式来尝试获取文章列表。