建立模型关系时相关字段的查找无效

时间:2021-07-19 10:27:01

标签: python django django-models django-related-manager

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


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)

我正在尝试过滤具有 LoanApplication 关系的 occupation group 模型,以下是职业组列表:

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

1 个答案:

答案 0 :(得分:1)

您使用冒号:)而不是等号(=)将参数传递给函数,因此您应该使用以下内容进行过滤:

LoanApplication.objects.filter(
    loan_taker__persons__person__occupational_group__in=['pharmacist']
)

因为你只匹配一个具有一个项目的列表,你可以用:

替换它
LoanApplication.objects.filter(
    loan_taker__persons__person__occupational_group='pharmacist'
)