I create base model and inherit that in all of my models. This is my 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)
Now, I want to add some operations to save
method of one of child models like this:
class Child(BaseModel):
# Some fields go here.
def save(self, *args, **kwargs):
# Some operations must run here.
But save
method of child model does n't run anymore!
How can I use save method of child model with save method of abastract=True
model?
If you inherit ChildModel from BaseModel, when you get to the save method in BaseModel 'self.class' is still ChildModel. So it finds the super of Child, which is BaseModel, so calls the save in BaseModel.
So just call ,
super(ChildModel, self).save(*args, **kwargs)