Django对象过滤器无法识别相关名称

时间:2017-03-30 20:05:10

标签: django django-models

使用Django 1.7

此控制台日志演示了此问题。 “职位”相关字段无法识别。

29         %put NOTE: %sysfunc(libname(maps));
NOTE: -630193

以下是Person,PersonAssociation和Position的模型类。为什么它适用于PersonAssociation但不适用于Position?

    x = Person.objects.get(PersonSk=452)

    x.Positions
    <django.db.models.fields.related.RelatedManager object at 0x0000000005B4A358>

    x.Associations
    <django.db.models.fields.related.RelatedManager object at 0x0000000005AEDC18>

    Person.objects.filter(Associations__isnull=True)
    [lots of peeps]

    Person.objects.filter(Positions__isnull=True)
raise_field_error
    "Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword 'Positions' into field.

据我所知,related_name字段的设置方式与两者相同?我还尝试将Position中的related_name更改为“Plops”,并使用相同的结果重新编写测试。

这是另一个控制台日志,我认为更好地说明了问题。在Positions模型中,我将Role字段和Person字段配置为具有相同的相关名称。所以我尝试了这个:

class Person(models.Model):
    class Meta:
        managed = False
        db_table = 'PERSON].[Person'
        ordering = ('LastName', 'FirstName')

    PersonSk = models.AutoField(primary_key=True, editable=False)
    FirstName = CharNullField('First Name', max_length=30, blank=True)
    LastName = CharNullField('Last Name', max_length=30, blank=True)
    Email = CharNullField(max_length=50, blank=True)
    PhoneWork = CharNullField('Work Phone', max_length=20, blank=True)
    PhoneMobile = CharNullField('Mobile Phone', max_length=20, blank=True)


class PersonAssociation(models.Model):
    class Meta:
        managed = False
        db_table ='CLIENT].[PersonAssociation'

    PersonAssociationSk = models.AutoField(primary_key=True, editable=False)
    Client = models.ForeignKey(Client, db_column='ClientCode', related_name='Associations')
    Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Associations')


class Position(models.Model):
    class Meta:
        managed = False
        db_table = 'PERSON].[Position'

    PositionSk = models.AutoField(primary_key=True, editable=False)
    Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Positions')
    ConsumerClient = models.ForeignKey(Client, db_column='ClientCode', related_name='Positions')
    ProviderClient = models.ForeignKey(Client, db_column='ProviderClientCode', related_name='ProviderPositions', blank=True, null=True)
    Role = models.ForeignKey(ContactRole, db_column='ContactRoleSk', related_name='Positions')
    Facility = models.ForeignKey(Facility, db_column='FacilitySk', blank=True, null=True)
    Notes = models.TextField(blank=True, null=True)
    StartDate = models.DateField()
    EndDate = models.DateField(blank=True, null=True)

所以它看起来特别是过滤功能无效?

1 个答案:

答案 0 :(得分:0)

这里的问题是Positions不是字段,而是关系。如果您想要一个零职位的员工列表,您需要进行聚合,然后对该聚合进行过滤。

这样的事情:

Person.objects.annotate(
    positions_count=Count('Positions')
).filter(positions_count=0)