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.
1
24
3/30/2009 11:24:00 PM

Accepted Answer

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, ...]
70
9/4/2013 1:25:12 PM

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon