如何设置manytomanyfield的默认值

时间:2012-04-21 18:14:26

标签: django django-models django-forms many-to-many

是否有办法绕过“实例需要在使用多对多关系才能使用主键值”错误?

我有一个包含多个字段的模型,包括与另一个模型的多对多关系。我有一个函数在我创建模型的新实例时在这些字段上设置默认值。我在处理HTTP GET时在视图中执行此操作。 m2m字段使用formset进行渲染。

以下是一些描述情况的伪代码:

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))

有什么建议吗?

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

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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