django - How to call the child model class from an abstract base class
This is going to be a short post. I recently had to write an abstract base class for a couple of models. The problem I encountered was that I needed to call the actual model class from a method that I defined in the abstract base class. And I was stuck.
Solution¶
The solution is to use the _meta
API. If you're thinking that the name
_meta
is private and therefore unsafe to use. It's not private. The leading
underscore is there to avoid confusion with the the name Meta
class of the
models. So, it is safe to use.
To access the actual model class in a method in your abstract base class, you can
use self._meta.model
.
Here's a code example:
class MyBase(models.Model):
...
def save(self, *args, **kwargs):
if self.pk:
instance = self._meta.model.objects.get(pk=self.pk)
...
class Meta:
abstract = True
That's it¶
I created this post because I couldn't find any resources online about this.
Hope it helps you, too.