"Related Field got invalid lookup: contains" 尝试在 Django 中搜索 ManyToMany 字段时

"Related Field got invalid lookup: contains" when attempting to search a ManyToMany field in Django

我正在使用 Django 3.2 和 Python 3.9。我有这个带有 ManyToMany 字段的模型

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)

然后我创建了这个查询来查找一个帐户,如果它包含来自多对人字段的项目

class AccountManager(models.Manager):
    def get_active(self, crypto_currency=None):
        q = Q()
        q &= Q(active=True)
        if crypto_currency != None:
            q &= Q(crypto_currencies__contains=crypto_currency)
        return Account.objects.filter(q)

但这似乎不起作用。我得到这个错误

 line 1184, in build_lookup
    raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))
django.core.exceptions.FieldError: Related Field got invalid lookup: contains

构造 Django 查询以搜索 ManyToMany 字段的正确方法是什么?

如果我理解你的问题,那么这是:-

class Account(models.Model):
     crypto_currencies = models.ManyToManyField(CryptoCurrency)

解决方法 :-

class Account(models.Model):
         crypto_currencies = models.ManyToManyField('CryptoCurrency',related_name='cryptoCurrency')

如果 crypto_currency 是一个 CryptoCurrency 实例,则您不需要包含查找

    if crypto_currency is not None:
        q &= Q(crypto_currencies=crypto_currency)