简体   繁体   English

Django:如何使用values_list属性编写GET查询?

[英]Django: How to write a GET query, using values_list attribute?

I want to query a model, for single instance (eg., id=1 ), but I only want to return the value of a single field ( 'title' ). 我想查询一个模型,对于单个实例(例如, id=1 ),但我只想返回单个字段的值( 'title' )。 I can achieve this with the following query: 我可以通过以下查询实现此目的:

SomeModel.objects.filter(pk=1).values_list('title', flat=True)

But a get is more efficient than a filter . 但是getfilter更有效。 However, values_list and values don't work with get queries. 但是, values_listvalues不适用于get查询。 Ideally, I would prefer to do this: 理想情况下,我更愿意这样做:

SomeModel.objects.get(pk=1).values_list('title', flat=True)

But I get the following error: AttributeError: SomeModel has no attribute 'title' 但是我收到以下错误: AttributeError: SomeModel has no attribute 'title'

What is the best way write this query? 编写此查询的最佳方法是什么?

But a get is more efficient than a filter . 但是getfilter更有效。

This is simply not true. 这是不正确的。 A .get(…) will generate exactly the same SQL as a .filter(…) . .get(…)将生成与.filter(…) 完全相同的SQL。

Using: 使用:

SomeModel.objects.filter(pk=1)[0:1].values_list('title', flat=True)

Will do what you want, and will have exactly the same performance characteristics as .get(…) (actually, it will be a bit faster, because .get(…) checks to see if more than one row would be returned…): 会做你想要的,并且将具有与.get(…)完全相同的性能特征(实际上,它会更快一点,因为.get(…)检查是否会返回多行......):

In [4]: import logging

In [5]: l = logging.getLogger("django.db")

In [6]: l.setLevel(logging.DEBUG)

In [7]: User.objects.filter(id=1)[0:1].values_list()
DEBUG:django.db.backends:(0.006) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1  LIMIT 1; args=(1,)
Out[7]: [(1, u'admin', u'Admin', u'User', u'admin@example.com', u'sha1$bf3bc$daa1fb58a8a41e15c730ae86bc0faf4c01fdd3a1', True, True, True, datetime.datetime(2013, 1, 8, 21, 15, 51, 855527), datetime.datetime(2012, 1, 10, 15, 13, 55))]

In [8]: User.objects.get(id=1)
DEBUG:django.db.backends:(0.001) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 ; args=(1,)
Out[8]: <User: admin>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM