django使用模型字段名

时间:2017-08-02 10:46:16

标签: django django-models django-annotate

我有以下型号

class Status(object):
    FIRST_STATUS = 'FS'
    SECOND_STATUS = 'SS'

    CHOICES = ((FIRST_STATUS, 'First Status'), (SECOND_STATUS, 'Second Status')

class MyModel(models.Model):
    status = models.CharField(max_length=2, choices=Status.CHOICES)

我试图注释状态字段,以便结果保存可读值而不是状态代码。 这就是我想要做的事情:

MyModel.objects.annotate(status=Case(When(status=Status.FIRST_STATUS, then='First Status'), When(status=Status=SECOND_STATUS, then='Second Status'), output_field=CharField())).values('status')

结果是例外:

`ValueError: The annotation 'status' conflicts with a field on the model.`<br/>
Which was not surprising because of [this][1] but what is, is that i can do this:<br/><br/>      


MyModel.objects.extra(select={'status': "CASE WHEN status='FS' THEN 'First Status' WHEN status='SS' THEN 'Second Status' ELSE 'Unknown status' END"}).values('status')

为什么要限制注释而不是在额外中验证相同的行为?是否有任何方法可以覆盖注释限制并省去手动构建查询?

1 个答案:

答案 0 :(得分:0)

请勿在汇总中使用status,请尝试:

MyModel.objects.annotate(
    status_display=Case(
        When(status=Status.FIRST_STATUS, then='First Status'), 
        When(status=Status.SECOND_STATUS, then='Second Status'),
    ),
    output_field=CharField()
).values('status_display')

更好:您不需要Case-WhenStatus课程。 Django可以处理:

在models.py中:

class MyModel(models.Model):
    FIRST_STATUS = 'FS'
    SECOND_STATUS = 'SS'
    CHOICES = (
        (FIRST_STATUS, 'First Status'), 
        (SECOND_STATUS, 'Second Status')
    )
    status = models.CharField(max_length=2, choices=CHOICES)

然后:

my_models = MyModel.objects.all()  # Or filter or any QuerySet
for model in my_models:
    status_description = model.get_status_display()

查看here了解详情。