Skip to main content
 首页 » 编程设计

python之获取字段查询值的元组

2025年05月04日16Terrylee

我想获取一些对象的 ID。将它们放入元组的干净方法是什么?

一个 .values() 查询集返回这个:

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

我想将它们转换成一个元组,例如:

(20L, 21L, 84L) 

请您参考如下方法:

最简单的解决方案是使用 flat=True 获取 values_list

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: