相关字段在建立模型关系时得到无效查找

Related Field got invalid lookup while making a model relationship

我正在尝试建立遍历不同模型的关系,但出现此错误:


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(
    <strong>loan_taker__persons__person__occupational_group__in=['pharmacist']</strong>
)

因为您只与包含 一个 项目的列表匹配,您可以将其替换为:

LoanApplication.objects.filter(
    loan_taker__persons__person__<strong>occupational_group='pharmacist'</strong>
)