我有以下型号
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')
为什么要限制注释而不是额外验证相同的行为?有什么方法可以覆盖对注释的限制并节省我手动构建查询的时间吗?