1

我有以下型号

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')

为什么要限制注释而不是额外验证相同的行为?有什么方法可以覆盖对注释的限制并节省我手动构建查询的时间吗?

4

1 回答 1

1

不要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()

在这里查看更多信息。

于 2017-08-02T13:58:23.450 回答