我有兩個模型指定用於跟蹤哪些用戶已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()
的方式完成,如果兩個模型鏈接。