Question

I have a model like this:

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)

And now in my view I want to filter so that the logged in user can se all Posts that the person follows. And the problem is that more people can follow the same Post.

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))

Is there a way of doing this?

Was it helpful?

Solution

Have a look at the docs.

You should be able to do do -

Post.objects.filter(followers__in=[user])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top