如何检索Django中所有对象的字段列表?

[英]How can I retrieve a list of field for all objects in Django?


I want to retrieve a list of all of the values for one field from a query in django. For example, I have a query of users, but rather than a queryset (or list) of user objects, I want a list just the usernames (strings). In a sense this is asking to restrict only to one column of data.

我想从django中的查询中检索一个字段的所有值的列表。例如,我有一个用户查询,但不是用户对象的查询集(或列表),我想要一个列表只是用户名(字符串)。从某种意义上说,这要求仅限制一列数据。

2 个解决方案

#1


25  

Have you tried

你有没有尝试过

User.objects.all().values_list('username', flat=True) 

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.

如果只传入单个字段,则还可以传入flat参数。如果为True,则表示返回的结果是单个值,而不是一个元组。

#2


6  

To get the list of usernames:

要获取用户名列表:

>>> User.objects.all().values('username')
>>> [{'username': u'u1'}, {'username': u'u2'}]

>>> User.objects.all().values_list('username')
>>> [(u'u1',), (u'u2',)]

If you want just strings, a list comprehension can do the trick:

如果你只想要字符串,列表理解可以做到这一点:

>>> usr_names = User.objects.all().values('username')
>>> [u['username'] for u in usr_names]
>>> [u'u1', u'u2']

Using values_list:

使用values_list:

>>> usr_names = User.objects.all().values_list('username')
>>> [u[0] for u in usr_names]
>>> [u'u1', u'u2']

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/02/01/2468ab5958736af411f1202fa25cd08b.html



 
  © 2014-2022 ITdaan.com 联系我们: