获取 Django ManyToManyField 关系定义的所有对象

发布于 2024-10-04 05:32:49 字数 803 浏览 1 评论 0原文

我正在构建的网站允许用户创建“帖子”,并具有类似 Twitter 的关注用户概念。对于给定用户,我想显示他们关注的用户的所有帖子。

以下是我的简化模型:

class User
    # a standard django.contrib.auth user model

class UserProfile(models.Model):
    # my AUTH_PROFILE_MODULE for django-profiles
    user = models.ForeignKey(User, unique=True)
    following = models.ManyToManyField('self', symmetrical=False, related_name="followed_by")

class Posts(models.Model):
    user = models.ForeignKey(User)
    post = models.TextField()

问题:如何从给定用户关注的用户创建所有 Post 对象的查询集?

我认为我通过在 UserProfile 上创建“follow”关系使事情变得更加复杂,这不是具有与 Posts 的foreignkey关系的模型。

更新!答案如下:

Posts.objects.filter(user__userprofile__in=UserProfile.objects.get(user=your_user_object).following.all())

The site I'm building allows users to create "posts" and has a Twitter-like concept of followed users. For a given user, I'd like to show all of the posts from the users that they follow.

Here are my simplified models:

class User
    # a standard django.contrib.auth user model

class UserProfile(models.Model):
    # my AUTH_PROFILE_MODULE for django-profiles
    user = models.ForeignKey(User, unique=True)
    following = models.ManyToManyField('self', symmetrical=False, related_name="followed_by")

class Posts(models.Model):
    user = models.ForeignKey(User)
    post = models.TextField()

Question: How do you create a queryset of all Post objects from the Users that a given User is following?

I think I've made it more complicated by creating the "follow" relationship on UserProfile, which is not the model with the ForeignKey relationship with Posts.

UPDATE! Here's the answer:

Posts.objects.filter(user__userprofile__in=UserProfile.objects.get(user=your_user_object).following.all())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁与争疯 2024-10-11 05:32:49
Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文