Member-only story
How Django Uses Metaclasses For Data Modelling
Before you continue reading: this is an intermediate-and-above level Python article. In order to fully engage with the concepts in this article, you’ll need to be familiar with basic Django concepts and have a solid grasp of Python’s object-oriented programming model.
Django is one of the most widely-used, open-source Python web frameworks within the Python community, with many of its built-in tooling assuming developers will work within a Model-View-Template (MVT) design pattern.
Most developers never have a chance to see the inner workings of Django. We’ll narrow our focus specifically to looking at Django’s class-based declarative data model approach, and how Django provides a cleaner interface for developers using metaclasses.
We’ll start by building a simple example application called exclusions. If we want to represent a Student, we would encapsulate both the schematic (what are the attributes, data types, and relatonships of this student?) and functional behavior (how would our student hypothetically display_status_towards_graduation()?) in a class definition within our app’s Python package, usually within a file called models.py:

