擅长:python、mysql、java
<p>这里有一个解决方案。也许还有更好的办法,但这应该行得通。循环检查formset中的所有表单,并更改<code>toppings</code>字段上的<code>choices</code>变量。像这样:</p>
<pre><code>pizza_form = PizzaFormSet(request.POST or None)
choices = [(t.pk, unicode(t)) for t in restaraunt.toppings.all().order_by('-id')]
for form in pizza_form:
form.fields['toppings'].choices = choices
</code></pre>
<p>您还可以重写<code>BaseModelFormset</code>并重写<code>_contruct_forms</code>方法,将restaraunt对象传递给表单的<code>__init__</code>,然后在那里更改topping的选择。但我认为上述解决方案是最快和最简单的。它只是引入了一个额外的循环。在</p>