如何重命名Django中的值()中的项目? [英] How to rename items in values() in Django?
本文介绍了如何重命名Django中的值()中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要像在 djangoproject.com 上的这张票一样做,但是有一些额外的格式。从这个查询
I want to do pretty much the same like in this ticket at djangoproject.com, but with some additonal formatting. From this query
>>> 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}]
还有另外一种,更内置的方式还是手动执行?
Is there another, more builtin way or do I have to do this manually?
推荐答案
这有点恶作剧,但您可以使用 extra
方法:
It's a bit hacky, but you could use the extra
method:
MyModel.objects.extra(select={'renamed_value': 'cryptic_value_name'}).values('renamed_value')
这基本上在SQL中 SELECT cryptic_value_name AS renamed_value
另一个选项,如果你总是想要重命名的版本,但数据库具有隐含的名称,是使用新名称命名您的字段,但使用 db_column
以引用数据库中的原始名称。
Another option, if you always want the renamed version but the db has the cryptic name, is to name your field with the new name but use db_column
to refer to the original name in the db.
这篇关于如何重命名Django中的值()中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文