【发布时间】:2019-10-22 04:12:24
【问题描述】:
我想用数据库中的数据填充表单下拉列表。 这些数据并非直接来自模型,而是来自原始查询。
当数据库可用且已生成迁移时,此功能有效。否则,生成迁移 (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()))
我天真地尝试手动更新__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=[]))
如何正确填写按需选择?
【问题讨论】:
-
您的第一个解决方案不起作用,因为您可能正在视图中的某处导入
MyForm(在任何 manage.py 操作期间启动 django 时导入),因此函数 @987654327 @ 被评估。您的第二个解决方案应该可以工作。 -
作为一个兴趣点,你为什么不定义一个模型来表示你的部门表?
-
我没有充分的理由不这样做。顺便说一句,在实际应用程序中,我可能会这样做。我正在开发的应用程序更像是一个发现和评估 Django 功能的玩具。
标签: django django-forms