Consider the following Friendship model, where for every friendship made, there is a User who sent the friend request, and a User who received the friend request:
from django.contrib.auth.models import User
class Friendship(models.Model):
sender = models.ForeignKey(User)
receiver = models.ForeignKey(User)
How would I construct a query that would give me all the usernames of the Users who are in a Friendship with, say, user123?
Keep in mind, user123 could be the sender or the receiver of any friendship he is in.
Also, I only want User.username values to be returned, not an entire User object.
So far, I have this clunky half/solution (I'm using list()
so that I can add both user123's receiving friends and user123's sending friends, to eventually produce a list of all friends). The problem is, I'm getting all the User objects, and I only want the usernames...and there's gotta be a better way to do this.
friends_a = list(Friendship.objects.filter(sender=user123).values('receiver'))
friends_b = list(Friendship.objects.filter(receiver=user123).values('sender'))
friends_a = [] if not friends_a else friends_a[0].values()
friends_b = [] if not friends_b else friends_b[0].values()
all_friends = friends_a + friends_b
Q Objects for complex lookups.
Wow, this is surprisingly a mind bender to get the result set you want since there's actually 2 different logical queries. The simplest way is ... to spell it out with python.
user = User.objects.get(username='user123')
friendships = Friendship.objects.filter(Q(receiver=user) | Q(sender=user))
usernames = []
for friendship in friendships:
if friendship.receiver == user:
usernames.append(friendship.receiver.username)
else:
usernames.append(friendship.sender.username)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With