How to insert Django SELECT?

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

I would like to select all to_friends that have from_friend = specific user.

Then, I would like to pass to_friends for the internal filter to another .objects.filter (). Is this a way to do this?

Thanks!

+3
source share
3 answers

As pccardune says, you get the appropriate users as follows:

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

But in fact, you can pass this directly to your next request:

second_select = Whatever.objects.filter(friend__in=friendships)
+2
source

I would like SELECTall to_friendsfor which from_friend= a specific User.

You can get all Friendship objects for this step like this:

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

to_friend , values_list :

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

friends - ValuesListQuery, , . filter().

+3

This seems to return the desired results.

User.objects.filter(to_friend_set__from_friend=1)
+2
source

Source: https://habr.com/ru/post/1719775/


All Articles