django - 如何从 Django 中的查询集中获取列表

标签 django

考虑以下 django 代码

phonenumbers = othermodel.objects.filter( company=mymodel.company,
                                         date_overwritten__isnull=True
                                       ).values_list('id', flat=True)

这返回另一个 QuerySet 对象而不是 python 列表,返回的查询集中的第一个对象是一个 {valuesListQuerySet},它是一个空列表,这是正确的,因为我的整个模型/表 othermodel 当前为空

我错过了什么?我如何获取 {valuesListQuerySet} 作为普通的 python 列表,即使它是空的

最佳答案

作为django doc says

If you don’t pass any values to values_list(), it will return all the fields in the model, in the order they were declared.

Note that this method returns a ValuesListQuerySet. This class behaves like a list. Most of the time this is enough, but if you require an actual Python list object, you can simply call list() on it, which will evaluate the queryset.

所以你可以调用:

list(phonenumbers)

关于django - 如何从 Django 中的查询集中获取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27293081/

相关文章:

mysql - 运行链接到我的 Django 项目的 mysql 数据库

django - 我可以在 django 模型中指定从某个值派生的上传文件夹吗?

Django 应用程序重定向所有 URL

python - Django 外键选择

python - Django 中的 "save and add another"(不是管理员): submit then pre-populate one field of form

python - pydev eclipse 上的 django 交互式 shell 出错

django - DRF 在接收请求时检查 DB 中是否已存在对象

django - 添加大整数(11 个字符)时针对 django 中的列警告调整的超出范围值

python - Django最佳实践中执行os和子进程

python - 当 DEBUG=False 时,Django 不在 Heroku 上提供静态文件