On Jul 1, 8:59 pm, Rajesh D <rajesh.dha...@gmail.com> wrote:
> On Jul 1, 9:50 am, Mathieu Leplatre <leplat...@gmail.com> wrote:
> > On 1 juil, 14:44, coan <a.ne...@gmail.com> wrote:
>
> > > I have a friendship model for users and want to retrieve all the posts
> > > my friends made.
>
> > > class Friendship(models.Model):
> > >  from_friend = models.ForeignKey( User, related_name='friend_set' )
> > >  to_friend = models.ForeignKey( User, related_name='to_friend_set' )
>
> > > class Post(models.Model):
> > >  text = models.TextField()
> > >  user = models.ForeignKey(User)
>
> > > I retrieve my friends posts with this:
>
> > > my_friendships = Friendship.objects.filter(from_friend=request.user)
> > > list_of_my_friends_ids = []
>
> > > for friendship in my_friendships:
> > >  list_of_my_friends_ids.append(friendship.to_friend.id)
>
> You can do the above with a one-liner:
>
> list_of_my_friends_ids = Friendship.objects.filter
> (from_friend=request.user).values_list('id', flat=True)
>

No, not quite. The OP wanted - and Mathieu's method provided - a way
to get the ids of the *friends*. Your query gets the ID of the
*friendships*, which isn't the same thing at all. This would work:
Friendship.objects.filter(from_friend=request.user).values_list
('to_friend_id', flat=True)
since the 'to_friend' FK is stored in the Friendship model as
'to_friend_id'.

However, the OP might be able to do the whole thing in one query.
Without testing, this *might* work:
Post.objects.filter(user__friend_set__to_friend=request.user)
--
DR.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to