3

有没有办法解决“实例需要有一个主键值才能使用多对多关系”错误?

我有一个包含多个字段的模型,包括与另一个模型的多对多关系。当我创建模型的新实例时,我有一个函数可以在这些字段上设置默认值。我在处理 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))

有什么建议么?

我怀疑我可能需要在表单端而不是模型端处理这个问题,但这也让我感到困惑。

4

2 回答 2

2

对于 1.3.1 中对我有用的表单:

与此类似,初始中的多对多

带有硬编码 ID:

def MyView(request):
    if request.method == 'GET':
        model   = MyModel( name = "my default name")
        initial = { 'relatedModels': [1,] } # assuming you knew the id and wanted to hardcode it
        form = MyForm( instance=model, initial=initial )
        return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))

使用查询按名称填充:

def MyView(request):
    if request.method == 'GET':
        model   = MyModel( name = "my default name")
        initial = { 'relatedModels':  [ o.pk for o in list(MyRelatedModel.objects.filter( name__in=("related model 1", "related model 2", "related model 3")))], } 
        form = MyForm( instance=model, initial=initial )
        return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))
于 2012-04-27T17:43:32.577 回答
1
for name in ["related model 1", "related model 2", "related model 3"]:
    relatedModel = MyRelatedModel(name=name)
    relatedModel.save()
    self.relatedModels.add(relatedModel)

或者:

newRelatedModels = []
for name in ["related model 1", "related model 2", "related model 3"]:
    relatedModel = MyRelatedModel(name=name)
    relatedModel.save()
    newRelatedModels.append(relatedModel)
self.relatedModels.add(*newRelatedModels)

这也应该有效:

self.relatedModels = newRelatedModels
于 2012-04-21T18:20:34.060 回答