有没有办法解决“实例需要有一个主键值才能使用多对多关系”错误?
我有一个包含多个字段的模型,包括与另一个模型的多对多关系。当我创建模型的新实例时,我有一个函数可以在这些字段上设置默认值。我在处理 HTTP GET 时在视图中执行此操作。m2m 字段使用表单集呈现。
下面是一些描述这种情况的伪代码:
class MyRelatedModel(models.Model):
name = models.CharField(max_length=100,blank=True)
class MyModel(models.Model):
name = models.CharField(max_length=100,blank=True)
relatedModels = models.ManyToManyField("MyRelatedModel")
def initialize(self):
self.name = "my default name"
# this bit doesn't really matter...
# just assume I am creating a new set of RelatedModels that I want to associate with my this new MyModel...
newRelatedModels = []
for name in ["related model 1", "related model 2", "related model 3"]:
relatedModel = MyRelatedModel(name=name)
relatedModel.save()
newRelatedModels.append(relatedModel.id)
self.relatedModels = newRelatedModels # this is invalid!
def MyView(request):
if request.method == 'GET':
model = MyModel()
model.initialize()
form = MyForm(instance=model)
return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))
有什么建议么?
我怀疑我可能需要在表单端而不是模型端处理这个问题,但这也让我感到困惑。