I have following code in models.py:

class Relationship(models.Model):
    from_person = models.ForeignKey(User, on_delete=models.CASCADE, related_name="from_person")
    to_person = models.ForeignKey(User, on_delete=models.CASCADE, related_name="to_person")

And this field defined in User model:
friends = models.ManyToManyField('self', blank=True, symmetrical=False, through='Relationship')

What I want is when I execute later in the view request.user.friends.all() to return only users which have symmetrical relationship with the logged-in user, because when I do this:
Relationship.objects.filter(from_person__in=request.user.friends.all(), to_person=request.user)
It returns Relationship objects of course, but I want to have the User ones like in the command above it.

The question is how to achieve that? I suppose that I have to make custom m2m manager and to somehow modify get_queryset() method.

up vote 0 down vote accepted

I've finally solved it with this command:
User.objects.filter(from_person__from_person__in=request.user.friends.all(), from_person__to_person=request.user)

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.