我如何从Django的queryset获取字符串表示形式 [英] How can i get the string representation from queryset in django

查看:233
本文介绍了我如何从Django的queryset获取字符串表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的查询集

qs = User.objects.all()

我要转换成这样的字典

qs.values('id','username' )

但我不想使用用户名来表示字符串表示形式。

but instead of username i want to get the string representation.

类似于

qs.values('id','__str __')

推荐答案

您不能,只能获取存储在数据库中的值,字符串表示形式不存储在

You cannot, values can only fetch values stored in the database, the string representation is not stored in the database, it is computed in Python.

您可以做的是:

qs = User.objects.all()
# Compute the values list "manually".
data = [{'id': user.id, '__str__': str(user)} for user in qs]

# You may use a generator to not store the whole data in memory,
# it may make sense or not depending on the use you make
# of the data afterward.
data = ({'id': user.id, '__str__': str(user)} for user in qs)

编辑:经过深思熟虑,根据您的字符串表示形式如何计算,可能可以使用 注释 查询表达式以达到相同的结果。

on second thought, depending on how your string representation is computed, it may be possible to use annotate with query expressions to achieve the same result.

这篇关于我如何从Django的queryset获取字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆