构造函数forms.ModelChoiceField需要一个查询集.在请求发生之前我不知道查询集.蒸馏:
# models.py
class Bar(models.model):
text = models.TextField()
class Foo(models.Model):
name = models.CharField()
bar = models.ForeignKey(Bar)
# forms.py
class FooForm(forms.Form):
name = forms.CharField()
text = forms.CharField(widget=forms.TextArea)
bar = forms.ModelChoiceField(queryset='??????')
Run Code Online (Sandbox Code Playgroud)
我目前在做什么:
# forms.py
def get_foo_form_class(bars_queryset):
class FooForm(forms.Form):
name = forms.CharField()
text = forms.CharField(widget=forms.TextArea)
bar = forms.ModelChoiceField(queryset=bars_queryset)
return FooForm
Run Code Online (Sandbox Code Playgroud)
然后我可以使用urlconf从url解析出的参数在视图中调用它来构造查询集并获取类.这感觉就像是错误的做法.有没有一种既定的方法在django做到这一点?