简体   繁体   中英

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 . That will give exactly what you want.

Assuming queryset is supposed to look like this, with 'x' and 'y' as string keys:

>>> 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:

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() :

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()

>>> 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

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

>>> 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.

为此使用values_list

result = User.objects.all().values_list("email", "name")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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