考虑:
>>>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.
原文由 Antonius Common 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
flat=True
django 查询集的构造: https ://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list从文档中的示例: