Get all objects defined by the Django ManyToManyField relation

The site I create allows users to create โ€œpostsโ€ and has the concept of following users on Twitter. For this user, I would like to show all messages from the users 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 set of requests for all Post objects from users to which this user is subject?

I think I made it more complicated by creating a "follow" relationship in UserProfile, which is not a model with ForeignKey relations with Posts.

UPDATE! Here is the answer:

Posts.objects.filter(user__userprofile__in=UserProfile.objects.get(user=your_user_object).following.all())
+5
source share
1 answer
Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
+7

All Articles