django - 如何通过多对多字段中的对象(完全匹配)过滤 django 模型?

标签 django django-models many-to-many django-orm

我的代码中有这个模型:

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

基本上有同样的问题。它产生在列表中具有一个或多个“参与者”的对象。但我正在寻找的是多对多对象的精确匹配。
意思是,在多对多关系上具有确切“用户”的对象。

编辑 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

最佳答案

好的,所以我找到了答案:
为了进行精确匹配,我必须对模型进行链式过滤,然后确保它具有所需的确切参数数量,以便多对多字段中包含 全部 需要的对象,没有更多。

我将使用注释检查对象编号:( https://docs.djangoproject.com/en/dev/topics/db/aggregation/ )

结束了这个代码:

def get_exist_conv_or_none(recipients):
    conv = Conversation.objects.annotate(count=Count('participants')).filter(participants=recipients[0])
    for participant in recipients[1:]:
        conv = conv.filter(participants=participant)
    conv = conv.filter(count=len(recipients))
    return conv

关于django - 如何通过多对多字段中的对象(完全匹配)过滤 django 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13586507/

相关文章:

django - 如何在 Django REST 框架中注册用户?

Django -- 无法导入我自己的模型

python - Rake:Django 中的任务等价物

Django——过滤时将多对多对象集视为一个实体

Django UserProfile匹配查询不存在

python - Django URL 与任何 URL 配置都不匹配

python - Django 表单错误 : Select a valid choice. 该选项不是可用选项之一

Django - 网络商店模型组织

entity-framework - Entity Framework 4 CTP 5 POCO - 多对多配置、插入和更新?

mysql - 多对多映射的 SQL 查询