我如何从 Django 中的查询集中获取字符串表示形式

How can i get the string representation from queryset in django

我有这样的查询集

qs = User.objects.all()

我正在像这样转换成 dict

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

但我想获取字符串表示而不是用户名。

类似

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

你不能,values只能获取存储在数据库中的值,字符串表示不存储在数据库中,它是在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)

编辑: 仔细想想,根据您的字符串表示形式的计算方式,使用 annotate with query expressions 可能会得到相同的结果。