[英]Python: Converting a queryset in a list of tuples
class User(models.Model):
email = models.EmailField()
name = models.CharField()
How to get email and name of User as a list of tuples?如何以元组列表的形式获取用户的电子邮件和名称? My current solution is this:
我目前的解决方案是这样的:
result = []
for user in User.objects.all():
result.append((user.email, user.name))
If this is an django ORM queryset (or result of it), you can just use values_list
method instead of values
.如果这是一个 django ORM 查询集(或它的结果),你可以只使用
values_list
方法而不是values
。 That will give exactly what you want.这将给出你想要的。
Assuming queryset
is supposed to look like this, with 'x'
and 'y'
as string keys:假设
queryset
应该是这样的, 'x'
和'y'
作为字符串键:
>>> queryset = [{'x':'1', 'y':'a'}, {'x':'2', 'y':'b'}]
>>> result = [(q['x'], q['y']) for q in queryset]
>>> result
[('1', 'a'), ('2', 'b')]
>>> # or if x and y are actually the correct names/vars for the keys
... result = [(q[x], q[y]) for q in queryset]
If you can have multiple keys and you just want certain key values, you can use itemgetter with map passing the keys you want to extract:如果您可以有多个键并且只需要某些键值,则可以使用itemgetter和 map 传递要提取的键:
from operator import itemgetter
result = list(map(itemgetter("x", "y"), queryset)))
your_tuple = [(x.get('attrA'), x.get('attrB')) for x in queryset.values()]
You can use dict.values()
:您可以使用
dict.values()
:
queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = []
for i in queryset:
result.append(tuple(i.values()))
Or in one line:或者在一行中:
result = [tuple(i.values()) for i in queryset]
If you want them in a particular order:如果您希望它们按特定顺序排列:
result = [(i[x], i[y]) for i in queryset]
Use list comprehension and dict.values()
使用列表理解和
dict.values()
>>> queryset = [{'x': '1', 'y': 'a'}, {'x': '2', 'y': 'b'}]
>>> result = [tuple(v.values()) for v in queryset]
>>> result
[('1', 'a'), ('2', 'b')]
UPDATE更新
as @aneroid reasonably mentioned, since dict
object are not ordered the code snippet could return different order in tuple
正如@aneroid 合理地提到的,因为
dict
对象没有排序,所以代码片段可能会在tuple
返回不同的顺序
So since i don't want to add duplicate solution.所以因为我不想添加重复的解决方案。 There is one option, not so elegant, and maybe with a lack of efficiency, to use
OrderedDict
有一种选择,不是那么优雅,而且可能缺乏效率,使用
OrderedDict
>>> from collections import OrderedDict
>>> queryset = [{'x': '1', 'y': 'a'}, {'x': '2', 'y': 'b'}]
>>> order = ('x', 'y')
>>> result = [tuple(OrderedDict((k, v[k]) for k in myorder).values()) for v in queryset]
>>> result
[('1', 'a'), ('2', 'b')]
But i personally think that @PadraicCunningham 's solution is the most elegant here.但我个人认为 @PadraicCunningham 的解决方案在这里是最优雅的。
为此使用values_list :
result = User.objects.all().values_list("email", "name")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.