我正在使用 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 欄位的正確方法是什么?
uj5u.com熱心網友回復:
如果crypto_currency是一個CryptoCurrency實體,則不需要包含查找
if crypto_currency is not None:
q &= Q(crypto_currencies=crypto_currency)
uj5u.com熱心網友回復:
如果我理解你的問題,那么這是:-
class Account(models.Model):
crypto_currencies = models.ManyToManyField(CryptoCurrency)
解決方案:-
class Account(models.Model):
crypto_currencies = models.ManyToManyField('CryptoCurrency',related_name='cryptoCurrency')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355225.html
標籤:姜戈 django-models 筛选 多对多
上一篇:為什么頁面上不顯示塊?
