我认为使用 django 表单可能是答案,如本文档中所述(搜索 m2m ...)。
编辑为可能有同样问题的其他人添加一些解释:
假设您有这样的模型:
from django.db import models
from django.forms import ModelForm
class Foo(models.Model):
name = models.CharField(max_length = 30)
class Bar(models.Model):
foos = models.ManyToManyField(Foo)
def __unicode__(self):
return " ".join([x.name for x in foos])
那么你不能在未保存的 Bar 对象上调用 unicode() 。如果您确实想在保存之前打印出来,您必须这样做:
class BarForm(ModelForm):
class Meta:
model = Bar
def example():
f1 = Foo(name = 'sue')
f1.save()
f2 = foo(name = 'wendy')
f2.save()
bf = BarForm({'foos' : [f1.id, f2.id]})
b = bf.save(commit = false)
# unfortunately, unicode(b) doesn't work before it is saved properly,
# so we need to do it this way:
if(not bf.is_valid()):
print bf.errors
else:
for (key, value) in bf.cleaned_data.items():
print key + " => " + str(value)
因此,在这种情况下,您必须保存 Foo 对象(您可以在保存这些对象之前使用它们自己的表单对其进行验证),并且在保存具有多对多键的模型之前,您也可以验证它们。所有这些都不需要过早地保存数据并弄乱数据库或处理事务......