views:

192

answers:

3
class Friendship(models.Model):
    from_friend = models.ForeignKey(User, related_name='friend_set')
    to_friend = models.ForeignKey(User, related_name='to_friend_set')

I'd like to SELECT all to_friends that have from_friend = a certain User.

Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it?

Thanks!

+3  A: 

I'd like to SELECT all to_friends that have from_friend = a certain User.

You could get all the Friendship objects for this step like so:

friendships = Friendship.objects.filter(from_friend=some_user)

Then you can get all the to_friend fields into a flat list using the values_list method of a query set:

friends = friendships.values_list("to_friend", flat=True)

At this point friends is a ValuesListQuery object that works just like a list. You can iterate over the friends and use the values in other filter() calls.

pcardune
Are there any alternatives?
TIMEX
+1  A: 

As pccardune says, you get the relevant users like this:

friendships = Friendship.objects.filter(from_friend=some_user)

But in fact you can pass this directly into your next query:

second_select = Whatever.objects.filter(friend__in=friendships)
Daniel Roseman
+1  A: 

This appears to return the desired results

User.objects.filter(to_friend_set__from_friend=1)
Adam