更新时间:2023-12-01 21:44:34
这里的问题是当模型仍在加载且应用未完全初始化时,您正在查询数据库:
The problem here is you're querying the database while models are still loading and apps are not fully initialized:
File "/Users/hugokitano/Documents/Summer_Code/statread/stats/models.py", line 40, in CompareForm
select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )
CONTROL_CHOICES
是先前在文件中定义的查询集:
CONTROL_CHOICES
is a queryset defined earlier in your file:
CONTROL_CHOICES = Control.objects.all()
为简单起见,请永远不要这样做。如果在未完全加载应用程序的情况下查询数据库,则所有内容都会崩溃。
To keep it simple, never, never do this. If you query the database while your apps are not fully loaded, everything will crash.
此外,您的代码也将无法正常运行:
Also, your code will not behave as expected:
class CompareForm(forms.Form):
select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )
因为您直接在查询集中迭代您的表单定义中,您将获得一个静态元素列表,这些元素在您重新启动服务器之前不会改变(即使您在数据库中添加了新元素)。
Since you are iterating on the queryset directly in your form definition, you will get a static list of elements that will never change (even if you add new ones in database) until you restart your server.
此处的解决方案是摆脱 forms.MultipleChoiceField
和 CONTROL_CHOICES
并使用 ModelMultipleChoiceField
。
专门针对这种情况设计:
The solution Here is to get rid of forms.MultipleChoiceField
and CONTROL_CHOICES
and use ModelMultipleChoiceField
.
It is designed specifically for this case:
class CompareForm(forms.Form):
select = forms.ModelMultipleChoiceField(queryset=Control.objects.all())
由于对查询集的计算是惰性的,显示表单时,您将直接从数据库获取最新的对象。
Django还将为您处理验证和所有操作。
As the queryset is lazily evaluated, you'll get up-to-dase objects straight from the database when displaying the form. Django will also handle validation and everything for you.