如何在django中仅获取表的特定列?

Ank*_*wal 29 python django

我看过这样的查询:

user = User.objects.all() or User.objects.filter(username = username)
Run Code Online (Sandbox Code Playgroud)

即使我们不需要所有列,也会获取表的所有列.我们有更好的方法来编写数据库查询吗?如果是,我们为什么不经常看到这个代码呢?

Ign*_*ams 32

QuerySet.only()并且QuerySet.defer()可以用于优化ORM将拉出哪些字段,推迟其他字段,直到访问模型上的适当属性.


max*_*max 26

使用django 1.8:使用values_list

Entry.objects.values_list('id', 'headline')
Run Code Online (Sandbox Code Playgroud)

https://docs.djangoproject.com/en/1.8/ref/models/querysets/


Avi*_*aor 6

如果您只需要将值作为字典使用objects.values('').它也更快.

见文档:http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields