[英]Python: Converting a queryset in a list of tuples
class User(models.Model):
email = models.EmailField()
name = models.CharField()
如何以元组列表的形式获取用户的电子邮件和名称? 我目前的解决方案是这样的:
result = []
for user in User.objects.all():
result.append((user.email, user.name))
如果这是一个 django ORM 查询集(或它的结果),你可以只使用values_list
方法而不是values
。 这将给出你想要的。
假设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]
如果您可以有多个键并且只需要某些键值,则可以使用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()]
您可以使用dict.values()
:
queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = []
for i in queryset:
result.append(tuple(i.values()))
或者在一行中:
result = [tuple(i.values()) for i in queryset]
如果您希望它们按特定顺序排列:
result = [(i[x], i[y]) for i in queryset]
使用列表理解和dict.values()
>>> queryset = [{'x': '1', 'y': 'a'}, {'x': '2', 'y': 'b'}]
>>> result = [tuple(v.values()) for v in queryset]
>>> result
[('1', 'a'), ('2', 'b')]
更新
正如@aneroid 合理地提到的,因为dict
对象没有排序,所以代码片段可能会在tuple
返回不同的顺序
所以因为我不想添加重复的解决方案。 有一种选择,不是那么优雅,而且可能缺乏效率,使用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')]
但我个人认为 @PadraicCunningham 的解决方案在这里是最优雅的。
为此使用values_list :
result = User.objects.all().values_list("email", "name")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.