I needed an abstract base class that can add attributes to the child classes based on the child's name. The attributes had to be implicit, but overridable, so all derived classes would get them by default, but they could be easily overriden in the child definition.
So, the code code I came up with basically consists of a customized metaclass used by the abstract model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class CustomModelBase (ModelBase):
"""Metaclass for AbstractModel"""
def __new__ (cls, name, bases, attrs):
""" Sets SOME_ID to match the child model's name,
if it's not explicitly set in the child model"""
model = super (CustomModelBase,cls).__new__(cls, name, bases, attrs)
if not (model._meta.abstract or hasattr(model,'SOME_ID')):
setattr(model,'SOME_ID',model._meta.object_name)
return model
class AbstractModel(models.Model):
"""This is the abstract class to be inherited by model classes.
You define some common stuff here """
__metaclass__ = CustomModelBase
class Meta:
abstract = True
# objects = SomeCustomManager()
# custom_field = models.CharField (...)
# etc abstract attributes
class ActualDataModel (AbstractModel):
""" This is the actual model describing data.
It inherits all attributes from the AbstractModel class.
By default ActualModel.SOME_ID will be equal to "ActualModel".
However, you can override this by setting it explicitly:"""
# SOME_ID = 'SomeFunnyID'
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.