menu

Questions & Answers

Django filter with Q objects not working or I am doing it wrong

I have this view to check if two users are friends and in this case they are because the logged in user and the author of the blog are indeed friends BUT the model for friendship only works one way and I need to make provision for that, which is why I wrote this function. After all if user1 is friends with user2 then automatically user2 is friends with user1:

The friendship model:

class Friendship(models.Model):
    person = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="person"
    )
    friend = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="friend"
    )

    created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")

The serializer method:

   def get_friends(self, obj):
        loggedUser = self.context.get('view').kwargs.get('user')
        post_author = obj.user_id
        friends = Friendship.objects.filter(Q(person=loggedUser), Q(friend=post_author) | Q(person=post_author), Q(friend=loggedUser))
        if friends:
            return True
        else:
            return False

Please tell me what I am doing wrong cause it says they are not friends even though they are?

Answers(1) :

I get what you're trying to do, but you'll have better luck constructing the AND logic a little differently.

Try putting each AND join inside of a Q object and joining those together with an OR operand.

Q(person=loggedUser, friend=post_author) | Q(person=post_author, friend=loggedUser)
Comments:
2023-01-24 00:55:06
Not really part of the answer, but you can also avoid that last if block by using return friends.exists().