B
B
Bjornie2017-10-08 23:47:42
Django
Bjornie, 2017-10-08 23:47:42

How to get a clean list from a query using values\values_list method in Django?

The question seems simple, but I didn't find a solution after a lot of googling and trying. And the task is simple: I want to get a clean list of identifiers (not a queryset and no other impurities, for example, with this query:

Mode.objects.filter(somefield__in=[1,2,3]).values_list('id', flat=True)
What I get is the qs objects in the list:
[<QuerySet [6]>, <QuerySet [3]>, <QuerySet [4]>, <QuerySet [12]>]
even if I list it with list().
And I would like to get something like: [45, 123, 34, 98], i.e. simple list. Tell me how it's done? How I solved this problem at the moment - 1) enclosing it in a list 2) converting the list to a string (str), 2) and then cutting out all the digits from the string using regex . Gross, but it works. But isn't there a simple method that will work the way I want?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
un1t, 2017-10-09
@un1t

ids = list(Mode.objects.filter(somefield__in=[1,2,3]).values_list('id', flat=True))

R
Rostislav Grigoriev, 2017-10-09
@crazyzubr

I guess instead:

# Select all load objects by date
loads = Load.objects.filter(date=datetime.now())
# loop through loads, in each iteration another loop with getting values ​​for rent_id
[i.values_list('rent_id', flat=True ) \
for i in [load.loadpara_set.all() for load in loads] if i]

Need like this:
list(LoadPara.objects.filter(load__date=datetime.now().date()).values_list('rent_id', flat=True))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question