我试图使关系遍历不同的模型,但遇到了以下错误:
django.core.exceptions.FieldError: Related Field got invalid lookup: occupational_group
以下是我的型号:
class LoanApplication(models.Model, TimeStampedModel):
loan_taker = models.ForeignKey(
CustomerProfile, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('Customer Profile'), related_name='loan_entries')
class CustomerProfile(models.Model, TimeStampedModel):
is_copy_component = models.BooleanField(
_('Is copy component'), default=False)
cooperation_partner = models.ForeignKey(
EmailUser, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('Jurisdiction'), related_name='partner_user_profile')
user = models.OneToOneField(
EmailUser, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('User'), related_name='user_profile')
approval_inquiry_sent_at = models.DateTimeField(
_('Approval inquiry sent at'), null=True, blank=True)
email_content_customer = models.FileField(
_('Content of the customer email'), upload_to="customer-emails/",
blank=True)
approved_at = models.DateTimeField(
_('Approved at'), null=True, blank=True)
class CustomerProfilePerson(models.Model, TimeStampedModel):
person = models.ForeignKey(
Person, on_delete=models.CASCADE,
verbose_name=_('Person'), related_name='customer_profile_relation')
customer_profile = models.ForeignKey(
CustomerProfile, on_delete=models.CASCADE,
verbose_name=_('Customer Profile'), related_name='persons')
class Person(models.Model, TimeStampedModel):
occupational_group = models.CharField(
_('Occupational group'), max_length=16, blank=True,
choices=OCCUPATIONAL_GROUP_CHOICES)
我试图用occupation group
的关系过滤LoanApplication
模型,下面是职业组的列表:
OCCUPATIONAL_GROUP_CHOICES = (
('pharmacist', _('Pharmacist')),
('architect', _('Architect')),
('doctor', _('Doctor')),
('consulting_eng', _('Consulting engineer')),
('notary', _('Notary')),
('psychotherapist', _('Psychotherapist')),
('lawyer', _('Lawyer')),
('tax_consultant', _('Tax Consultant')),
('vet', _('Vet')),
('sworn_auditor', _('Sworn auditor')),
('surveyor', _('Surveyor')),
('auditor', _('Auditor')),
('dentist', _('Dentist')),
('other', _('Other')),
)
所以这是我下面的查询,但失败了:
LoanApplication.objects.filter(loan_taker__persons__person__occupational_group__in: ['pharmacist'])
我得到了这个例外:
django.core.exceptions.FieldError: Related Field got invalid lookup: occupational_group
您用冒号(:
(而不是等号(=
(将参数传递给函数,因此您应该使用进行筛选
LoanApplication.objects.filter(
loan_taker__persons__person__occupational_group__in=['pharmacist']
)
由于您只匹配一个有一个项目的列表,因此您可以将其替换为:
LoanApplication.objects.filter(
loan_taker__persons__person__occupational_group='pharmacist'
)