【问题标题】:Get all objects defined by a Django ManyToManyField relationship获取由 Django ManyToManyField 关系定义的所有对象
【发布时间】:2010-11-26 18:43:13
【问题描述】:

我正在构建的网站允许用户创建“帖子”,并具有类似 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())

【问题讨论】:

    标签: django django-models manytomanyfield


    【解决方案1】:
    Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
    

    【讨论】:

    • 我收到 TypeError: 'ManyRelatedManager' 对象不可迭代
    • 哦,我忘了。在“关注”之后添加 .all(),例如“UserProfile.objects.get(user=your_user_object).following.all()”。如果不行,改成following.objects.all()。具体记不太清了。
    • 谢谢,修复了 TypeError,但仍有一些地方不太对劲,因为它返回的是一个空集。
    • 可能只是指定用户的“关注”字段为空?
    • 我正在测试的用户正在关注 3 个用户,他们总共创建了 32 个帖子。我认为它可能是在一组 UserProfiles 中寻找一个 User 对象?
    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2011-12-24
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多