How to get object using filter on ManyToManyField

891 views Asked by At

Why target_dialogue is always None?

Model:

class Dialogue(models.Model):
    name = models.CharField(max_length=30, blank=True)
    is_conference = models.BooleanField(default=False)

    participants = models.ManyToManyField(
        Person,
        related_name='dialogues',
    )

    def __str__(self):
        return self.name or str(self.pk)

And in view I want to get suitable dialogue which contain in participants field 2 objects - user and companion. And if this dialogue doesn't exist I create it:

        target_dialogue = None
        try:
            target_dialogue = Dialogue.objects.get(is_conference=False,participants__in=[user, companion])
        except ObjectDoesNotExist:
            target_dialogue = Dialogue()
            target_dialogue.save()
            target_dialogue.participants.add(user)
            target_dialogue.participants.add(companion)
        finally:
            return render(request, 'dialogues/dialogue.html', {
                'dialogue': target_dialogue,
            })

But target_dialogue is always None. What's a reason of it? I was supposed to solve only a trouble in getting a dialogue from db in order to bad filter parameters, but now I have doubts about it. Maybe something else?

1

There are 1 answers

3
Pranav Aggarwal On BEST ANSWER

request.user is not a object of Person model with which you have the relation in Dialogue.

You have to first fetch the person object:

user = Person.objecs.get(user=request.user). # According to your person model

Follow same for companion and then query:

target_dialogues = Dialogue.objects.filter(is_conference=False,participants__in=[user,companion]