使用数据库(但不是模型)中的选择填充 Django 表单字段

Alb*_*urg 1 django django-forms

我想用数据库中的数据填充表单下拉列表。这些数据不是直接来自模型,而是来自原始查询。

当数据库可用并且迁移已生成时,此功能有效。否则,生成迁移 ( python manage.py makemigrations myapp) 会失败,因为 Django 评估_all_departments()无法找到合适的表。

def _all_departments() -> List[Tuple[str, str]]:
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("select distinct department from crm_mytable order by department")
        return [(row[0], row[0]) for row in cursor.fetchall()]


class MyForm(forms.Form):
    department = forms.CharField(
        widget=forms.SelectMultiple(choices=_all_departments()))
Run Code Online (Sandbox Code Playgroud)

我天真地尝试手动更新选项,但__init__没有成功(选项始终为空):

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['department'].widget.choices = _all_departments()

    department = forms.CharField(
        widget=forms.SelectMultiple(choices=[]))
Run Code Online (Sandbox Code Playgroud)

正确填写按需选择的方法是什么?

Wil*_*sem 5

应该将 传递choices小部件,而应该传递给字段。您还可能想使用MultipleChoiceField[Django-doc],这使用SelectMultiple[Django-doc]作为默认小部件:

class MyForm(forms.Form):

    department = forms.MultipleChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['department'].choices = _all_departments()
Run Code Online (Sandbox Code Playgroud)