考虑:
>>>jr.operators.values_list('id')
[(1,), (2,), (3,)]
如何进一步简化:
['1', '2', '3']
目的:
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.
答案 0 :(得分:70)
使用django查询集的flat=True
结构:https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list
来自文档中的示例:
>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]
答案 1 :(得分:3)
你需要做..来获得这个输出[' 1',' 2',' 3']
map(str, Entry.objects.values_list('id', flat=True).order_by('id'))
答案 2 :(得分:0)
您可以使用列表理解:
>>> mylist = [(1,), (2,), (3,)] >>> [str(x[0]) for x in mylist] ['1', '2', '3']
答案 3 :(得分:0)
这样的东西?
x = [(1,), (2,), (3,)]
y = [str(i[0]) for i in x]
['1', '2', '3']