我创建基础模型并在我的所有模型中继承它。这是我的BaseModel:class BaseModel(models.Model): create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) created_by = models.ForeignKey('UserManager.User', default=1, on_delete=models.SET_DEFAULT,related_name='created_%(class)ss') updated_by = models.ForeignKey('UserManager.User', default=1, on_delete=models.SET_DEFAULT,related_name='updated_%(class)ss') class Meta: abstract = True ordering = ['create_date'] def save(self, *args, **kwargs): self.user = kwargs.pop('user', None) if self.user: if self.user.pk is None: self.created_by = self.user self.updated_by = self.user super(BaseModel, self).save(*args, **kwargs)现在,我想向save其中一个子模型的方法添加一些操作,如下所示:class Child(BaseModel): # Some fields go here. def save(self, *args, **kwargs): # Some operations must run here. 但是savechild model的method已经跑不起来了!如何将子模型的保存方法与abastract=True模型的保存方法一起使用?
1 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
如果你从BaseModel继承ChildModel,当你到达BaseModel'self.save方法时。类' 仍然是 ChildModel。所以它找到了Child的super,也就是BaseModel,所以调用了BaseModel中的save。
所以只要打电话,
super(ChildModel, self).save(*args, **kwargs)
添加回答
举报
0/150
提交
取消