5

我正在构建的网站允许用户创建“帖子”,并具有类似 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 上创建“关注”关系使其变得更加复杂,这不是与 Posts 的 ForeignKey 关系的模型。

更新!这是答案:

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

1 回答 1

7
Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
于 2010-11-26T18:48:16.307 回答