1

I know that I can get ForeignKey and ManyToManyField attributes by Blog.objects.values('name', 'entry_headline'), is there anyway to get choices value in the same way? I mean Blog.objects.values('name', 'choices_values') rather than using get_FOO_display().

4

2 回答 2

2

模型.py

class MyModel(models.Model)
    ALL = "ALL"
    NONE = "NONE"
    HALF = "HALF"
    SELECT_CHOICES = (
        (ALL, "100%"),
        (HALF, "50%"),
        (NONE, "0%"),
    )
    select_field = models.CharField(max_length = 255, choices = SELECT_CHOICES)

    @property
    def select_ratio(self):
        return self.get_select_field_display()

任何地方:

mymodels = MyModel.objects.all()
for entry in mymodels:
    print entry.select_ratio
于 2013-08-07T15:58:18.180 回答
0

鉴于显示字符串包含在 Python 中,除非您像这样手动设置,否则实际上无法在数据库查询中提供它们:

from django.db.models import Case, Value, When

Blog.objects.values('name').annotate(
    status_verbose=Case(
        When(status=PENDING, then=Value('Pending')),
        When(status=PUBLISHED, then=Value('Published')),
        default=Value('Draft'),
        output_field=CharField(),
    )
)

案例的 Django 文档

于 2020-12-17T20:48:07.890 回答