0

我创建基本模型并在我的所有模型中继承它。这是我的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. 

但是save子模型的方法不再运行了!
如何将子模型的保存方法与abastract=True模型的保存方法一起使用?

4

1 回答 1

1

如果你从 BaseModel 继承 ChildModel,当你到达 BaseModel 'self.save 方法时。class ' 仍然是 ChildModel。所以它找到了Child的super,也就是BaseModel,所以调用了BaseModel中的save。

所以只要打电话,

super(ChildModel, self).save(*args, **kwargs)
于 2020-06-29T12:06:41.670 回答