如果ManyToManyField包含指定的用户,我如何过滤它?

时间:2013-02-22 10:39:55

标签: python django filter manytomanyfield

我有一个这样的模型:

from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    followers = models.ManyToManyField(User, null=True, blank=True)

现在在我看来,我希望进行过滤,以便登录用户可以查看该人员关注的所有帖子。问题是更多人可以关注同一个帖子。

def get_followed_posts(request):  
    user = request.user  
    posts = Post.objects.filter(followers__contains=user) # If the user is in the list of followers return the Post.
    return render_to_response('post_list.html', {'posts': posts}, context_instance=request_context(request))

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

查看docs

你应该可以做 -

Post.objects.filter(followers__in=[user])