擅长:python、mysql、java
<p>嗯,我成功地实现了我想要的。正如@Alasdair建议的那样,我创建了一个中介模型。在</p>
<pre><code>class Model1(models.Model):
name = models.Charfield(...)
muscles = models.ManyToManyField(Model2, blank=True, null=True,)
class Model2(models.Model):
name = models.CharField(...)
field1 = models.CharField(...)
class Model1Model2(models.Model):
model1 = models.ForeignKey(Model1)
model2 = models.ForeignKey(Model2)
class MyForm(ModelForm):
muscles = forms.ModelMultipleChoiceField(
queryset=None,
to_field_name="field1", required=False,)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['muscles'].queryset = Model2.objects.all()
</code></pre>
<p>然后在save_model方法中,我可以遍历字段的值并保存它们。在</p>
<p>解决我问题的重点显然是中介模式。在</p>
<p>谢谢@Alasdair</p>