5

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())
mitchf
  • 3,697
  • 4
  • 26
  • 29

1 Answers1

7
Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)
Vladimir Lagunov
  • 1,895
  • 15
  • 15
  • I'm getting a TypeError: 'ManyRelatedManager' object is not iterable – mitchf Nov 26 '10 at 19:24
  • oh, i forgot. After "following" add .all(), like "UserProfile.objects.get(user=your_user_object).following.all()". If it doesn't work, change it to following.objects.all(). I don't remember exactly. – Vladimir Lagunov Nov 26 '10 at 19:30
  • Thanks, that fixed the TypeError, but something still isn't quite right as it is returning an empty set. – mitchf Nov 26 '10 at 19:57
  • maybe it's just empty "following" field of an specified user? – Vladimir Lagunov Nov 26 '10 at 20:00
  • The user I'm testing is following 3 users who have created a total of 32 posts. I think it may be looking for a User object in a set of UserProfiles? – mitchf Nov 26 '10 at 20:06