Login

Custom optional abstract base attributes

Author:
tie
Posted:
June 16, 2008
Language:
Python
Version:
.96
Tags:
model abstract
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. Binding signals to abstract models by andreterra 2 years, 10 months ago
  2. Change model field attribute in a DRY way by jedie 3 years, 5 months ago
  3. DRY with common model fields (another way) by jmrbcu 7 years, 8 months ago
  4. Multiple User subclasses custom Auth backend by ungenio41 3 years, 6 months ago
  5. Child aware model inheritance by rix 6 years, 4 months ago

Comments

Please login first before commenting.