Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all objects defined by a Django ManyToManyField relationship

The site I'm building allows users to create "posts" and has a Twitter-like concept of followed users. For a given user, I'd like to show all of the posts from the users that they follow.

Here are my simplified models:

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

Question: How do you create a queryset of all Post objects from the Users that a given User is following?

I think I've made it more complicated by creating the "follow" relationship on UserProfile, which is not the model with the ForeignKey relationship with Posts.

UPDATE! Here's the answer:

Posts.objects.filter(user__userprofile__in=UserProfile.objects.get(user=your_user_object).following.all())
like image 344
mitchf Avatar asked Nov 26 '10 18:11

mitchf


1 Answers

Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
like image 177
Vladimir Lagunov Avatar answered Oct 16 '22 12:10

Vladimir Lagunov