如何在 ManyToManyField 上使用过滤器获取对象

How to get object using filter on ManyToManyField

为什么 target_dialogue 总是 None?

型号:

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)

而且我想获得合适的对话,其中包含参与者字段 2 个对象 - 用户和同伴。如果这个对话不存在,我会创建它:

        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,
            })

但是 target_dialogue 总是 None。这是什么原因呢?我应该只解决从 db 获取对话的问题,以便过滤参数错误,但现在我对此有疑问。也许还有别的?

request.user 不是与您在对话中有关系的 Person 模型的对象。

您必须先获取人物对象:

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

跟随同伴,然后查询:

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