如何从django中的queryset获取字符串表示形式

时间:2023-01-27 16:05:29

I have the queryset like this

我有这样的查询集

qs = User.objects.all()

qs = User.objects.all()

I am converting to dict like this

我正在转变为这样的字典

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

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

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

但不是用户名我想得到字符串表示。

something like

就像是

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

qs.values('id','_ _ ttr__')

1 个解决方案

#1


6  

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.

你不能,值只能获取存储在数据库中的值,字符串表示不存储在数据库中,它是用Python计算的。

What you could do is:

你能做的是:

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)

Edit: 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.

编辑:第二个想法,根据您的字符串表示的计算方式,可以使用带有查询表达式的注释来实现相同的结果。

#1


6  

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.

你不能,值只能获取存储在数据库中的值,字符串表示不存储在数据库中,它是用Python计算的。

What you could do is:

你能做的是:

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)

Edit: 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.

编辑:第二个想法,根据您的字符串表示的计算方式,可以使用带有查询表达式的注释来实现相同的结果。