2012-07-31 162 views
0

我有兩個模型指定用於跟蹤哪些用戶已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管理兩個UserProfileUpvotedArticle類別。

但是,我不明白,爲什麼試圖獲取文章列表不能按照我最初嘗試使用a.articles_upvoted.all()的方式完成,如果兩個模型鏈接。

回答

2

因爲這些關係並不相同。通過在一側定義一個ForeignKey,在另一側定義一個ManyToMany,您已經爲數據庫提供了兩個單獨的位置來存儲有關文章upvoting的信息。

您應該刪除ManyToManyFieldUserProfile,並且只使用自動反向關係:

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

或者,你可以承認UpvotedArticle爲「通過」的多對多關係的表,它明確地標記爲這樣的在articles_upvoted定義 - 不過,請注意的關係應該是與articlescraper.Article,不UpvotedArticle

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

雖然您並未在該關係中添加任何額外數據,這是通過定義顯式通過表的常見原因,但您可能希望完全刪除它並僅依靠Django將創建的自動數據。

相關問題