Python/Django: Creating a simpler list from values_list()

Question:

Consider:

>>>jr.operators.values_list('id')
[(1,), (2,), (3,)]

How does one simplify further to:

['1', '2', '3']

The purpose:

class ActivityForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ActivityForm, self).__init__(*args, **kwargs)
        if self.initial['job_record']:
            jr = JobRecord.objects.get(pk=self.initial['job_record'])

            # Operators
            self.fields['operators'].queryset = jr.operators

            # select all operators by default
            self.initial['operators'] = jr.operators.values_list('id') # refined as above.
Asked By: Antonius Common

||

Answers:

You can use a list comprehension:

    >>> mylist = [(1,), (2,), (3,)]
    >>> [str(x[0]) for x in mylist]
    ['1', '2', '3']
Answered By: brian-brazil

Something like this?

x = [(1,), (2,), (3,)]
y = [str(i[0]) for i in x]
['1', '2', '3']
Answered By: Ken

Use the flat=True construct of the django queryset: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list

From the example in the docs:

>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]
Answered By: Jarret Hardie

You need to do ..to get this output [‘1’, ‘2’, ‘3’]

map(str, Entry.objects.values_list('id', flat=True).order_by('id'))

Answered By: Manjunath Raddi

To transform from a flat QuerySet :

Entry.objects.values_list('id', flat=True)

<QuerySet [1, 5]>

to a Python List, you can do this:

[*Entry.objects.values_list('id', flat=True)]

[1, 5]

Answered By: Léo Chaz Maltrait
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.