本文介绍了Python / Django:从values_list()创建一个更简单的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑: >>> jr.operators.values_list('id')
[ (1,),(2,),(3)]
:
['1','2','3']
/ pre>
目的:
类ActivityForm(forms.ModelForm )
def __init __(self,* args,** kwargs):
super(ActivityForm,self).__ init __(* args,** kwargs)
如果self.initial ['job_record ']:
jr = JobRecord.objects.get(pk = self.initial ['job_record'])
#运算符
self.fields ['operators']。queryset = jr.operators
#默认选择所有运算符
self.initial ['operators'] = jr.operators.values_list('id')#如上所述。
解决方案使用
flat = True
django查询器的构造:
从文档中的示例:
>>> Entry.objects.values_list('id',flat = True).order_by('id')
[1,2,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.
解决方案Use the
flat=True
construct of the django queryset: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_listFrom the example in the docs:
>>> Entry.objects.values_list('id', flat=True).order_by('id') [1, 2, 3, ...]
这篇关于Python / Django:从values_list()创建一个更简单的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!