gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:32:49 25 4
gpt4 key购买 nike

我想做与 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com