Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading