【问题标题】:Understanding Django's ORM (Database Design with ForeignKey and QuerySets)了解 Django 的 ORM(使用 ForeignKey 和 QuerySets 的数据库设计)
【发布时间】:2015-11-08 20:02:42
【问题描述】:

我需要一些帮助来了解 Django 1.8 的 ORM。我对如何正确实现数据库中的关系感到困惑。

我想要一个User 对象有一个UserProfile。我还需要一个User 才能制作几个Posts

然后我希望UserProfile 可以访问用户 发布的所有帖子,以便我可以在userprofile 视图中显示它们。我应该通过给Post 一个FK 给UserProfile 还是相反或根本不这样做?

如果这是正确的方法,我什至如何查询用户的所有帖子? 到目前为止,这是我的模型的代码:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True)
    biography = models.TextField(max_length=500, blank=True)
    likes = models.IntegerField(default=0, blank=True)
    dislikes = models.IntegerField(default=0, blank=True)
    slug = models.SlugField(max_length=50)

    def __unicode__(self):
        return unicode(self.user.username)


class Post(models.Model):
    user = models.ForeignKey(User,null=True)
    user_profile = models.ForeignKey(UserProfile, null=True)
    title = models.CharField(max_length=50, blank=False)
    body = models.TextField(max_length=500, blank=False)
    description = models.CharField(max_length=100, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    def __unicode__(self):
        return unicode(self.title)

我想我可能想多了这一切。我怀疑UserProfilePost 根本不需要关系,视图可以用这两个这样的QuerySet 呈现单独的数据吗? posts=Post.objects.filter(user=request.user)user_profile = UserProfile.objects.filter(user=request.user)

【问题讨论】:

    标签: django django-orm


    【解决方案1】:

    您不需要在 Post 模型上使用 user_profile FK。 如果您想访问用户创建的所有帖子以便在 UserProfile 上显示它们,您可以使用这个查询,给定一个 user_profile 实例:

    user_posts = user_profile.user.post_set.all()
    

    user_profile 具有用户属性,因为 OneToOne 字段具有 post_set 属性,该属性已链接到您的用户并为您提供该用户创建的所有帖子。此外,post_set 也是一个查询集,这意味着您也可以对其进行过滤:

    user_profile.user.post_set.filter(title__icontains='Django')
    

    以上代码将为您提供给定user_profile 标题中包含“django”的所有帖子。

    如需进一步参考,请参阅 related objectsfollowing relationships backward 上的 django 文档。

    【讨论】:

    • 哇太棒了。因此,如果我要通过视图呈现它们,我将不得不以某种方式通过 QuerySet 传递 request.user 参数,对吗? user_profile.user.post_set.all(instance=request.user) 之类的东西?
    • 您到底想通过视图渲染什么?如果是 Posts,您可以使用 Post.objects.filter(user=request.user),但为了完成此操作,您不需要 Post 和 UserProfile 之间的关系。
    • 啊,好吧,这很有意义。这回答了一切,谢谢!
    • 还有一件事...在 ForeignKey 关系上定义 related_name 参数是一个很好的做法,例如在 Post 模型中 - user = models.ForeignKey(User, null=True, related_name='posts')。因此,您的查询将类似于user_profile.user.posts.all(),更加清晰易懂。
    猜你喜欢
    • 2017-09-21
    • 2016-10-19
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2020-08-02
    • 2020-04-18
    相关资源
    最近更新 更多