Django查询ManyToMany字段报Related Field invalid lookup: contains如何解决
错误原因
__contains是Django专门用于字符串类型字段的查询运算符,不适用于多对多关系字段,因此会抛出Related Field got invalid lookup: contains的字段错误。
多对多字段的正确查询方式
多对多字段查询不需要额外的contains运算符,Django会自动处理中间表的关联逻辑,常见查询场景写法如下:
- 筛选包含单个指定关联实例的记录:直接用多对多字段名匹配实例即可
示例:filter(crypto_currencies=CryptoCurrency实例) - 筛选包含任意一个指定关联实例的记录:用
__in运算符传入实例列表
示例:filter(crypto_currencies__in=[实例1, 实例2]) - 筛选同时包含多个指定关联实例的记录:链式叠加多次filter即可
示例:filter(crypto_currencies=实例1).filter(crypto_currencies=实例2) - 如果你只拿到了关联对象的主键值,也可以通过字段+主键的方式查询:
filter(crypto_currencies__id=加密货币主键值)
修正后的自定义管理器代码
另外注意自定义管理器中不要直接调用Account.objects,应该调用self.get_queryset()获取基础查询集,避免后续扩展出现异常,完整修正代码如下:
import uuid from django.db import models from django.db.models import Q class AccountManager(models.Manager): def get_active(self, crypto_currency=None): # 先获取基础查询集,筛选活跃账户 queryset = self.get_queryset().filter(active=True) if crypto_currency is not None: # 直接匹配多对多关联项即可 queryset = queryset.filter(crypto_currencies=crypto_currency) return queryset # 别忘了在Account模型中绑定自定义管理器 class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=True) # ... 其他原有字段 crypto_currencies = models.ManyToManyField(CryptoCurrency) # 绑定管理器 objects = AccountManager()
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

