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
- Form field with fixed value by roam 2 weeks, 2 days ago
- New Snippet! by Antoliny0919 3 weeks, 1 day ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months, 1 week ago
- get_object_or_none by azwdevops 7 months ago
- Mask sensitive data from logger by agusmakmun 8 months, 4 weeks ago
Comments
Please login first before commenting.