Python/Django:从values_list()创建一个更简单的列表

时间:2021-08-28 21:27:34

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.

4 个解决方案

#1


68  

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

使用django queryset的flat=True结构:https://docs.djangoproject.com/en/dev/ref/models/querysets/# django.db.models.queryset.values_list

From the example in the docs:

从文档中的例子来看:

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

#2


3  

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

你需要做…要得到这个输出['1','2','3']

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

地图(str,Entry.objects。values_list(“id”,平= True).order_by(id))

#3


0  

You can use a list comprehension:

你可以使用列表理解:

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

#4


0  

Something like this?

是这样的吗?

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

#1


68  

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

使用django queryset的flat=True结构:https://docs.djangoproject.com/en/dev/ref/models/querysets/# django.db.models.queryset.values_list

From the example in the docs:

从文档中的例子来看:

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

#2


3  

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

你需要做…要得到这个输出['1','2','3']

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

地图(str,Entry.objects。values_list(“id”,平= True).order_by(id))

#3


0  

You can use a list comprehension:

你可以使用列表理解:

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

#4


0  

Something like this?

是这样的吗?

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