用Overriden Save扩展抽象模型的Django ModelForm

时间:2012-12-09 00:06:20

标签: django inheritance model modelform

所以我有这个类,它是一堆其他类的抽象父类,让我们称之为ActivityModel(表示某种最新的活动/或对该对象做的更改),我想重写save方法每次保存对象时都有另一个参数,所以我将其定义如下。

class ActivityModel(models.Model):
    last_updated = models.DateTimeField(auto_now=True)
    updater = models.ForeignKey(UserProfile)
    change = models.CharField(max_length=255)

    def save(self, updater, change, *args, **kwargs):
        self.updater = updater
        self.change = change
        super(ActivityModel, self).save(*args, **kwargs)

    class Meta:
        abstract = True

但是现在我继承这个类的所有模型都不能使用ModelForms,因为我已经将save方法更改为需要第二个字段(对应于经过身份验证的用户的UserProfile,每次保存时都必须提供)所以我想知道是否有可能将ModelForm类子类化为覆盖它的save方法,以便它将调用新的ParentModel.save方法并填写已提供给它的当前登录用户。我想我可以在表单init上提供UserProfile,但我最大的问题是是否可以继承ModelForm类并创建类似ParentModelForm类,然后可以为每个ParentModel的子类创建子类。这是可能的,如果可以的话,我该怎么做呢?

非常感谢所有帮助!谢谢你的时间!

1 个答案:

答案 0 :(得分:4)

ModelForm也是一个python类,其行为与其他类相似。

#Inherits from ModelForm class
class ParentModelForm(forms.ModelForm):
...
...
   def save(self, *args, **kwargs):
     ...
     ...
#Inherits from ParentModelForm
class ChildModelForm(ParentModelForm):
..
..
  #You would have to override the Meta class
  class Meta:
      model = Child
  def save(self, *args, **kwargs):
       #Calling the parent model form save method
       super(ChildModelForm, self).save(*args, **kwargs)