私のコードにはこのモデルがあります:
class Conversation(models.Model):
participants = models.ManyToManyField(User, related_name="message_participants")
そして、この「会話」モデルオブジェクトを「参加者」の多対多フィールドでフィルタリングする必要があります。意味:たとえば、3つのユーザーオブジェクトがあるので、「参加者」フィールドにこの3つのユーザーが含まれる「会話」オブジェクトのみを取得したいと思います。
私はこれをやってみました:
def get_exist_conv_or_none(sender,recipients):
conv = Conversation.objects.filter(participants=sender)
for rec in recipients:
conv = conv.filter(participants=rec)
ここで、senderはUserオブジェクトであり、「recipients」はUserオブジェクトのリストです。エラーは発生しませんが、間違った会話オブジェクトが表示されます。ありがとう。
編集:最近の試みは私をこれに導きます:
def get_exist_conv_or_none(sender,recipients):
participants=recipients
participants.append(sender)
conv = Conversation.objects.filter(participants__in=participants)
return conv
基本的に同じ問題があります。これにより、リストに1つ以上の「参加者」が含まれるオブジェクトが生成されます。しかし、Imが探しているのは、多対多のオブジェクトの完全一致です。つまり、正確な「ユーザー」が多対多の関係にあるオブジェクトです。
編集2:私の最後の試み。それでも、動作しません。
def get_exist_conv_or_none(sender,recipients):
recipients.append(sender)
recipients = list(set(recipients))
conv = Conversation.objects.annotate(count=Count('participants')).filter(participants=recipients[0])
for participant in recipients[1:]:
conv.filter(participants=participant)
conv.filter(count=len(recipients))
return conv