0

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?

1
  • Please only use the version tags, e.g. django-3.0 if your question is specifically about that version and the answers wouldn't be applicable for other (earlier or later) Django versions, for instance, version migration problems. Commented Jul 15, 2020 at 17:11

1 Answer 1

1

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) 
Sign up to request clarification or add additional context in comments.

9 Comments

I don't want to change save method of BaseModel. I just want to add somethings to save method of child model. @mohit-harshan
ok then just do the save() method in the abstract model and call super(BaseModel, self).save(*args, **kwargs) itwself . it will refer to child model save only
ty @mohit-harshan
@Whale52Hz: I tried combinations of the options suggested here - I think I didn't get it right. The scenario is not working. Could you pls let me know the following: 1. Have you kept the BaseModel as it is (at the top of the page)? 2. I tried the save() method in the ChildModel as super(BaseModel, self).save(*args, **kwargs) (i.e. placed the code in the model class of the child model). But unfortunately the field created_by is not getting updated at save. Could you please come back on this?
@carla How can I help you?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.