我知道我可以通过Blog.objects.values('name','entry_ headline')获取ForeignKey和ManyToManyField属性,无论如何都以相同的方式获得选择值?我的意思是Blog.objects.values('name','choices _values')而不是使用get_FOO_display()。
答案 0 :(得分:1)
models.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()
Anywhere的:
mymodels = MyModel.objects.all()
for entry in mymodels:
print entry.select_ratio
答案 1 :(得分: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(),
)
)