Login

Custom optional abstract base attributes

Author:
tie
Posted:
June 16, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 1 month, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 month, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 8 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 1 week ago
  5. Help text hyperlinks by sa2812 10 months, 1 week ago

Comments

Please login first before commenting.