django - 如何在 Django 中重命名 values() 中的项目?

标签 django django-orm

我想做与 this ticket at djangoproject.com 中几乎相同的事情, 但有一些额外的格式。来自这个查询

>>> MyModel.objects.values('cryptic_value_name')
[{'cryptic_value_name': 1}, {'cryptic_value_name': 2}]

我想得到这样的东西:

>>> MyModel.objects.values(renamed_value='cryptic_value_name')
[{'renamed_value': 1}, {'renamed_value': 2}]

还有其他更内置的方法还是我必须手动执行此操作?

最佳答案

django>=1.8 你可以使用 annotate 和 F object

from django.db.models import F

MyModel.objects.annotate(renamed_value=F('cryptic_value_name')).values('renamed_value')

extra() 也将被弃用,来自 django docs:

This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing extra(). We are no longer improving or fixing bugs for this method.

关于django - 如何在 Django 中重命名 values() 中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10598940/

相关文章:

python - 来自 django 教程 was_published_recently.admin_order_field = 'pub_date'

python - Django:将 views.py 分离到它自己的模块中是个好主意吗?

python - django:在 transaction.atomic() 内提交和提升

django - 使用 Django 的 ORM 进行复杂的 M2M 过滤

python - 我如何在 Django 中获取多对多关系表数据?

python - 在 Django 的 ORM 中使用带有 UPDATE 的子查询

python - 模型按日期默认排序,空值排在前面

python - 从 Pycharm 内部启动了一个 django 服务器,但现在我无法将其关闭

python - 如何修复 django-mptt 中没有 child 到 parent 的问题?

django 多数据库路由不适用于多个模式