【问题标题】:django annotating value with model field namedjango 用模型字段名称注释值
【发布时间】:2017-08-02 10:46:15
【问题描述】:

我有以下型号

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

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

【问题讨论】:

    标签: django django-models django-annotate


    【解决方案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()
    

    查看here了解更多信息。

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 2018-03-21
      • 2021-01-31
      • 2011-07-18
      • 1970-01-01
      • 2017-09-17
      • 2016-03-26
      • 1970-01-01
      • 2015-06-07
      相关资源
      最近更新 更多