0

我指定了两个模型来跟踪用户对文章实例的支持(在另一个应用程序中,在这种情况下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 管理员的UserProfileUpvotedArticle类别中。

a.articles_upvoted.all()但是,我不明白,如果两个模型链接在一起,为什么不能按照我最初尝试使用的方式来尝试获取文章列表。

4

1 回答 1

2

因为这不是同一个关系。通过在一侧定义 ForeignKey 和在另一侧定义 ManyToMany,您为数据库提供了两个单独的位置来存储有关文章投票的信息。

您应该删除ManyToManyFieldon UserProfile,并使用自动反向关系:

a = UserProfile.objects.get(pk=1)
a.upvotedarticle_set.all()

或者,您可以将其识别UpvotedArticle为 ManyToMany 关系的“通过”表,并在 -note 的定义中明确标记它,articles_upvoted尽管该关系应该是 with articlescraper.Article,而不是UpvotedArticle

article_upvoted = models.ManyToManyField(articlescraper.Article, null=True,
                                         blank=True, through=UpvotedArticle)

尽管由于您没有在该关系上添加任何额外数据(这是定义显式直通表的常见原因),但您可能希望完全删除它,而只依赖 Django 将创建的自动数据。

于 2012-07-31T07:00:23.870 回答