Home > Software design >  "Related Field got invalid lookup: contains" when attempting to search a ManyToMany field
"Related Field got invalid lookup: contains" when attempting to search a ManyToMany field

Time:11-10

I'm using Django 3.2 and Python 3.9. I have this model with a ManyToMany field

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?

CodePudding user response:

If crypto_currency is a CryptoCurrency instance you do not need to include the lookup

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

CodePudding user response:

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')
  • Related