获取字段查询值的元组

2024-04-24 09:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一些物体的身份证。什么是让它们进入元组的干净方法?在

A.values()queryset返回:

MyModel.objects.filter(name__startwith='A').values('id')
>>>> [{'id': 20L}, {'id': 21L}, {'id': 84L}]

我想把它们转换成一个元组,比如:

^{pr2}$

Tags: 方法nameidobjectsfiltermymodel物体queryset
2条回答

生成器表达式呢?在

tuple(d['id'] for d in MyModel.objects.filter(name__startwith='A').values('id'))

或者:

^{pr2}$

或者,正如出于某种原因被删除的答案所建议的那样,您可以这样做:

^{3}$

或者:

import operator
getter = operator.attrgetter('id')
tpl = tuple(map(getter, MyModel.objects.filter(name__startwith='A')))

最简单的解决方案是用flat=True得到{}

models.MyModel.objects.all().values_list('id', flat=True)

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call — so the first item is the first field, etc.

If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples. An example should make the difference clearer:

相关问题 更多 >