gpt4 book ai didi

python - Django:将 'choices' 从另一个数据库传递到 MultipleChoiceField

转载 作者:行者123 更新时间:2023-12-01 06:44:25 24 4
gpt4 key购买 nike

我有一个模型,其中有一个应该是多选的字段。我为此创建了一个ModelForm。在此,我查询另一个数据库以获得用户应该能够选择的可能选项。

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__'

MultipleChoiceField 仅采用元组作为选择参数。碰巧这正是 cursor.fetchall() 返回的结果。唯一的问题是这个元组看起来像这样:

(('value1',), ('value2',),...))

由于元组中没有第二个值,django 会抛出错误:

not enough values to unpack (expected 2, got 1)

元组应该是不可变的,所以我觉得以某种方式再次添加相同的值以使错误消失是非常hacky的。另一方面,将元组放入列表,然后再次放入元组似乎也是错误的。有更好的方法吗?

最佳答案

您需要键值对,例如:

class CollaborationForm(forms.ModelForm):
cursor = connections['diseases'].cursor()
cursor.execute('select some_column from some_table')
all_cuis = cursor.fetchall()
cui = forms.MultipleChoiceField(
<b>choices=[(c[0],c[0]) for c in all_cuis]</b>,
help_text='Relevant CUI, can select more than one'
)

class Meta:
model = Collaboration
fields = '__all__'

但请注意,在加载 CollaborationForm 类时,您只会运行查询一次。您可能希望将选项的创建移至 __init__ 方法。例如:

class CollaborationForm(forms.ModelForm):
cui = forms.MultipleChoiceField(
<b>choices=[]</b>,
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()
<b>self.fields['cui'].choices = [c*2 for c in all_cuis]</b>

class Meta:
model = Collaboration
fields = '__all__'

关于python - Django:将 'choices' 从另一个数据库传递到 MultipleChoiceField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com