Django 检查是否存在多对多关系

Django check if many-to-many relationship exists

我在 Django 中有一种社交网络,人们可以在其中发送直接消息。在所有这些消息中,我有一个对话字段来显示消息之间的人员,这样我就可以在向用户显示消息时按人对消息进行分组。

我想知道如何搜索对话是否存在。在视图下方的打印语句中,我返回:

<QuerySet [<Conversation: Sarah and Stephen>, <Conversation: Sarah and James>]>

<QuerySet [<User: Sarah>, <User: Stephen>]>

<QuerySet [<User: Sarah>, <User: James>]>

在下面的视图中,发送者是 'Sarah',接收者是 'James',所以我想弄清楚如何搜索他们之间的对话是否已经存在(通过过滤器或其他东西)通过将它们与上面的各种 QuerySet 列表匹配,如果是这样,我可以使用该对话,如果不是,我可以创建对话。我尝试了很多东西,但一直卡住了。我对多对多关系还很陌生。

景色

def writemessage(request, id):
    profile = Profile.objects.get(id=id)
    context = {
        'profile': profile,
    }
    conversations = Conversation.objects.all()
    print(conversations)
    for each in conversations:
        print(each.participants.all())
    if request.method == 'POST':
        sender = request.user
        receiver = profile.user
        content = request.POST['content']
        timestamp = datetime.now()
        record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp)
        record.save()
        senderprofile = Profile.objects.get(user=sender)
        receiverprofile = Profile.objects.get(user=receiver)
        # below is where the code breaks
        record.conversation.add(senderprofile)
        record.conversation.add(receiverprofile)
        return redirect('messagespage')
    return render(request, 'thecode/writemessage.html', context)

我的模特

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=60)
    country = models.CharField(max_length=60)
    skillstolearn = models.CharField(max_length=200)
    skillstoteach = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.user.username

class Conversation(models.Model):
    participants = models.ManyToManyField(User)
    
    def __str__(self):
        return str(self.participants.all()[0]) + ' and ' + str(self.participants.all()[1])

要查找 M2M 仅包含这 2 个用户的对话,您可以使用 chain filters() and use exists() 检查这 2 个用户之间是否存在该对话:

sarah_user = User.objects.get(username="Sarah")
stephen_user = User.objects.get(username="Stephen")
Conversation.objects.filter(participants=sarah_user).filter(participants=stephen_user).exists()