Django ORM get respective choices value instead of field value

时间:2018-02-03 10:32:19

标签: python django orm django-orm

In Django ORM, is there any way that you can directly get the respective choices value instead of the field value in the resulting Queryset.
Example:

port = models.CharField(
  max_length=5,
  choices=( ('21', 'FTP'), ('22', 'SSH'), (...), .. )
)

After the ORM Querying, I need the port name (not the number) in the Queryset itself.

Query:

> myModel.objects.filter(...).values()

output:

> [{"id": 1, "port": "21"}, {"id": 2, "port": "22"}, {...}, ...]

What i want:

> [{"id": 1, "port": "FTP"}, {"id": 2, "port": "SSH"}, {...}, ...]

1 个答案:

答案 0 :(得分:1)

正如@neverwalkaloner指出的那样,您不会在数据库中保存“FTP”等,因此无法使用您的查询集检索它们。你能做的就是这样:

[{'id': obj.pk, 'port': obj.get_port_display()} for obj in myModel.objects.filter(...)]

这会给你:

[{"id": 1, "port": "FTP"}, {"id": 2, "port": "SSH"}, {...}, ...]

希望它有所帮助。