简体   繁体   English

如何在Django上列出与多体关系的对象? 示例:用户和关注

[英]How to list objects with relationship manytomany on Django? example: users and follows

I was make a microblogging like twitter and I want to list the posts of users that authenticated user is following. 我当时像微博一样成为微博,我想列出经过身份验证的用户正在关注的用户的帖子。

Models: 楷模:

class Post(models.Model):
    post = models.TextField(max_length=300)
    created = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.post

class UserProfile(models.Model):
    USER_SEX = (
        ('M', 'Masculino'),
        ('F', 'Femenino'),
    )
    birthday = models.DateField(null=False)
    sex = models.CharField(max_length=1, choices=USER_SEX)
    description = models.TextField(max_length=100, null=True)
    location = models.CharField(blank=True, max_length=100, null=True)
    user = models.OneToOneField(User)
    follows = models.ManyToManyField('UserProfile', related_name='followed_by', blank=True, symmetrical=False)

    def __unicode__(self):
            return self.user.get_username()

Views: 观看次数:

def show_posts(request):
    user = request.user
    following = user.userprofile.follows.all()
    posts = Post.objects.filter(user__in=following).order_by('-created')
    return render_to_response("posts.html", context_instance = RequestContext(request, {'posts':posts}))

This function return all posts of all users, except the authenticated user. 此功能返回除已认证用户之外的所有用户的所有帖子。 I don't want this. 我不要这个 I want to show all posts of users ONLY the user authenticated is following and also the posts of the user authenticated. 我只想显示已验证用户的所有用户帖子以及已验证用户的帖子。

Someone can help me? 有人可以帮我吗?

I'm not sure of my answer, but nobody answered, so here's my try. 我不确定我的回答,但没有人回答,所以这是我的尝试。

following is a QuerySet, which becomes a list of UserProfile , but you filter on user__in , which is a list of User . following是一个QuerySet,它成为UserProfile的列表,但您对user__in过滤,后者是User的列表。 Can you try making follows a ManyToManyField to User instead and tell us the results? 您能尝试follows User的ManyToManyField来告诉我们结果吗? Even if you still have the same problem, the filter will make more sense! 即使您仍然遇到相同的问题,过滤器也会更有意义!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM