是否有办法解决“在使用多对多关系之前实例需要具有主键值”的错误?

我有一个具有多个领域的模型,其中包括与另一个模型的多对多关系。当我创建模型的新实例时,我具有一个在这些字段上设置默认值的功能。我在处理HTTP GET时在 View 中执行此操作。使用表单集渲染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))

有什么建议么?

我怀疑我可能需要在表单方面而不是模型方面进行处理,但这也使我感到困惑。

最佳答案

对于表格,在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))

关于django - 如何为manytomanyfield设置默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10261671/

10-15 23:27