我认为使用django表单可能是答案,如本文档中概述(搜索m2m
…)。
编辑后为可能遇到相同问题的其他人添加了一些解释:
说您有一个这样的模型:
from django.db import modelsfrom django.forms import ModelFormclass Foo(models.Model): name = models.CharField(max_length = 30)class Bar(models.Model): foos = models.ManyToManyField(Foo) def __unipre__(self): return " ".join([x.name for x in foos])
那么您将无法在未保存的Bar对象上调用unipre()。如果您确实想在保存之前打印出所有内容,则必须执行以下操作:
class BarForm(ModelForm): class meta: model = Bardef 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, unipre(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对象(在保存之前,可以使用它们自己的形式进行验证),并且在保存具有很多对很多键的模型之前,您也可以对其进行验证。所有这些都无需太早保存数据并弄乱数据库或处理事务…



