python / expert
Snippet
Custom Model Metaclass for Dynamic Model Attribute Injection
In modern Django architecture, custom metaclasses extending `ModelBase` allow developers to hook into the Python class creation lifecycle before model fields are registered. By overriding `__new__`, you can conditionally inject ORM field instances and dynamic helper methods into non-abstract subclasses programmatically.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
from django.db import modelsfrom django.db.models.base import ModelBaseclass DynamicAuditMeta(ModelBase):def __new__(mcs, name, bases, attrs):if not attrs.get('__abstract__', False):attrs['audit_version'] = models.IntegerField(default=1)attrs['get_audit_tuple'] = lambda self: (self.pk, self.audit_version)return super().__new__(mcs, name, bases, attrs)class AuditedModel(models.Model, metaclass=DynamicAuditMeta):class Meta:abstract = True
django
Breakdown
1
from django.db.models.base import ModelBase
Imports Django's core metaclass responsible for constructing model classes and registering fields.
2
class DynamicAuditMeta(ModelBase):
Defines a custom metaclass extending ModelBase to customize class creation behavior.
3
def __new__(mcs, name, bases, attrs):
Intercepts class allocation, receiving metaclass, class name, base classes, and attribute dictionary.
4
if not attrs.get('__abstract__', False):
Checks if the class being created is a concrete model class rather than an abstract model.
5
attrs['audit_version'] = models.IntegerField(default=1)
Dynamically injects a Django IntegerField definition into the class attributes dictionary before creation.
6
attrs['get_audit_tuple'] = lambda self: (self.pk, self.audit_version)
Attaches a dynamic helper method to the model class dictionary to return audit state.
7
return super().__new__(mcs, name, bases, attrs)
Delegates actual class creation to ModelBase.__new__ with modified attributes.