ユーザーがArticleインスタンス(この場合は別のアプリ)に賛成したものを追跡するために指定された2つのモデルがあります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シェルでは、次の操作を行って記事のリストを取得しようとしました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()
ただし、 2つのモデルがリンクされている場合、記事のリストを取得しようとして最初に使用した方法で取得できない理由はわかりません。