Python Django:将“选项”从另一个数据库传递到多个EchoiceField
我有一个模型,它有一个字段,应该是多选的。我已经为此创建了一个模型表单。在本例中,我查询另一个数据库,以获取用户应该能够从中选择的可能选项Python Django:将“选项”从另一个数据库传递到多个EchoiceField,python,django,Python,Django,我有一个模型,它有一个字段,应该是多选的。我已经为此创建了一个模型表单。在本例中,我查询另一个数据库,以获取用户应该能够从中选择的可能选项 class CollaborationForm(forms.ModelForm): cursor = connections['diseases'].cursor() cursor.execute('select some_column from some_table') all_cuis = cursor.fetchall()
class CollaborationForm(forms.ModelForm):
cursor = connections['diseases'].cursor()
cursor.execute('select some_column from some_table')
all_cuis = cursor.fetchall()
cui = forms.MultipleChoiceField(choices=all_cuis, help_text='Relevant CUI, can select more than one')
class Meta:
model = Collaboration
fields = '__all__'
MultipleChiceField只接受一个元组作为参数。恰好这正是cursor.fetchall返回的结果。唯一的问题是这个元组看起来像这样:
(('value1',), ('value2',),...))
由于元组中没有第二个值,django会抛出错误:
not enough values to unpack (expected 2, got 1)
元组应该是不可变的,所以我觉得以某种方式再次添加相同的值以消除错误是非常困难的。另一方面,将元组放入列表,然后再次放入元组似乎也是错误的。有更好的方法吗?您需要键值对,例如:
class CollaborationForm(forms.ModelForm):
cursor = connections['diseases'].cursor()
cursor.execute('select some_column from some_table')
all_cuis = cursor.fetchall()
cui = forms.MultipleChoiceField(
choices=[(c[0],c[0]) for c in all_cuis],
help_text='Relevant CUI, can select more than one'
)
class Meta:
model = Collaboration
fields = '__all__'
太快了。。!如果我在所有CUI中使用[c,c代表c],它会抱怨太多的值。[c[0],c[0]代表所有的c[u cuis]成功了。谢谢@Snackoverflow:或者您可以使用c*2生成两次包含项的元组。我不知道这是一件事:。看起来也很好,看起来更干净。再次感谢。
class CollaborationForm(forms.ModelForm):
cui = forms.MultipleChoiceField(
choices=[],
help_text='Relevant CUI, can select more than one'
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
cursor = connections['diseases'].cursor()
cursor.execute('select some_column from some_table')
all_cuis = cursor.fetchall()
self.fields['cui'].choices = [c*2 for c in all_cuis]
class Meta:
model = Collaboration
fields = '__all__'