简体   繁体   中英

Get tuple of field query value

I want to get ids of some objects. What is the clean way to get them in tuple?

A .values() queryset return this:

MyModel.objects.filter(name__startwith='A').values('id')
>>>> [{'id': 20L}, {'id': 21L}, {'id': 84L}]

And i would like transform/get them into a tuple like:

(20L, 21L, 84L)

The simplest solution is to get values_list with flat=True

models.MyModel.objects.all().values_list('id', flat=True)

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call — so the first item is the first field, etc.

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. An example should make the difference clearer:

What about a generator expression?

tuple(d['id'] for d in MyModel.objects.filter(name__startwith='A').values('id'))

Alternatively:

import operator
tuple(map(lambda x: operator.getitem(x, 'id'), MyModel.objects.filter(name__startwith='A').values('id'))

Or, as an answer that was deleted for some reason suggested, you could do this:

tuple(object.id for object in MyModel.objects.filter(name__startwith='A'))

Alternatively:

import operator
getter = operator.attrgetter('id')
tpl = tuple(map(getter, MyModel.objects.filter(name__startwith='A')))

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