tags:

views:

546

answers:

3

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

You can use a list comprehension:

    >>> mylist = [(1,), (2,), (3,)]
    >>> [str(x[0]) for x in mylist]
    ['1', '2', '3']
A: 

Something like this?

x = [(1,), (2,), (3,)]
y = [str(i[0]) for i in x]
['1', '2', '3']
Ken
this is a re-implementation of an API available in django that will be much slower than django's generated SQL query
Jarret Hardie
+6  A: 

Use the flat=True construct of the django queryset: http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list-fields

From the example in the docs:

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