Django:将另一个数据库中的“选项”传递到多个EchoIceField

2024-04-25 08:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型,有一个字段应该是多选的。我已经为此创建了一个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)

元组应该是不可变的,所以我觉得以某种方式再次添加相同的值以消除错误是非常困难的。另一方面,把元组变成一个列表,然后再变成元组似乎也是错误的。有没有更好的方法?你知道吗


Tags: 用户模型数据库错误formssomeallselect
1条回答
网友
1楼 · 发布于 2024-04-25 08:26:59

您需要键值对,例如:

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

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

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

相关问题 更多 >