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

标签 python django

我想获取一些对象的 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:

关于python - 获取字段查询值的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19706305/

相关文章:

python - 使用全局包的 windows virtualenv

python - 在空的 Pandas DataFrame 中插入单元格

python - Python 中的类似工具? (来自 Ruby 的工具)

python - 将颜色图应用于 Matplotlib 3D 表面中的自定义轴

django - 最大图像上传大小验证 Django REST API

python - Elasticsearch dsl删除错误

python - 更改元组列表,使第一个条目与第二个条目相同

python - PyMongo 与 Django 和 uwsgi

python - 哪种算法可以合理地减少多个列表? ("who killed who"问题)

javascript - Django 表单和缓存控制的问题