简体   繁体   English

尝试在 Django 中搜索 ManyToMany 字段时出现“Related Field got invalid lookup: contains”

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

I'm using Django 3.2 and Python 3.9.我正在使用 Django 3.2 和 Python 3.9。 I have this model with a ManyToMany field我有一个带有 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)

Then I have created this query to find an account if it contains an item from teh many-to-man field然后我创建了这个查询来查找一个帐户,如果它包含来自多对人字段的项目

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)

but this doesn't seem to be working.但这似乎不起作用。 I get this error我收到这个错误

 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

What's the right way to construct a Django query to search a ManyToMany field?构建 Django 查询以搜索 ManyToMany 字段的正确方法是什么?

If I understand your problem so this is:-如果我理解你的问题,那么这是:-

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

Solution :-解决方案:-

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

If crypto_currency is a CryptoCurrency instance you do not need to include the lookup如果crypto_currencyCryptoCurrency实例,则不需要包含查找

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM