在Google App Engine中的ModelForm中设置父级

时间:2010-01-19 21:27:36

标签: python django google-app-engine app-engine-patch

我想在通过ModelForm创建的实体中创建实体组关系。

如何传递父实例并在ModelForm中设置parent=属性?

2 个答案:

答案 0 :(得分:4)

我有兴趣看看你是否能找到解决这个问题的好办法。我自己的解决方案远非优雅,就是这样做:

book = models.Book(title='Foo')
chapter = models.Chapter(parent=book, title='dummy')
form = forms.ChapterForm(request.POST, request.FILES, instance=chapter)

基本上,我首先使用正确的父关系创建一个虚拟对象(在这种情况下为chapter),然后将其作为instance参数传递给表单的构造函数。表单将覆盖我用来创建虚拟对象的一次性数据和请求中给出的数据。最后,为了获得真正的子对象,我做了类似的事情:

if form.is_valid():
    chapter = form.save()
    # Now chapter.parent() == book

答案 1 :(得分:0)

我继承了djangoforms.ModelForm并添加了一个创建方法*:

class ModelForm(djangoforms.ModelForm):
  """Django ModelForm class which uses our implementation of BoundField.
  """

  def create(self, commit=True, key_name=None, parent=None):
    """Save this form's cleaned data into a new model instance.

    Args:
      commit: optional bool, default True; if true, the model instance
        is also saved to the datastore.
      key_name: the key_name of the new model instance, default None
      parent: the parent of the new model instance, default None

    Returns:
      The model instance created by this call.
    Raises:
      ValueError if the data couldn't be validated.
    """
    if not self.is_bound:
      raise ValueError('Cannot save an unbound form')
    opts = self._meta
    instance = self.instance
    if self.instance:
      raise ValueError('Cannot create a saved form')
    if self.errors:
      raise ValueError("The %s could not be created because the data didn't "
                       'validate.' % opts.model.kind())
    cleaned_data = self._cleaned_data()
    converted_data = {}
    for name, prop in opts.model.properties().iteritems():
      value = cleaned_data.get(name)
      if value is not None:
        converted_data[name] = prop.make_value_from_form(value)
    try:
      instance = opts.model(key_name=key_name, parent=parent, **converted_data)
      self.instance = instance
    except db.BadValueError, err:
      raise ValueError('The %s could not be created (%s)' %
                       (opts.model.kind(), err))
    if commit:
      instance.put()
    return instance

用法很简单:

book = models.Book(title='Foo')
form = forms.ChapterForm(request.POST)
chapter = form.create(parent=book)

请注意,我没有复制/粘贴允许您在request.POST中指定key_name的代码,而是将其作为参数传递给create。

*代码是根据google.appengine.ext.db.djangoforms中原始模型的保存方法修改的。