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:
That’s more or less it from a developer’s perspective. From there, Django handles all the boilerplate plumbling code to sync your new data model with a backend database table via manage.py makemigrations exclusions, with validating and persisting new instances of Student, enforcing foreign key relationships and constraints, etc. This is traditionally the domain boundary contract between Django web developer and a Django source contributor- you declare your model classes to conform to a specific pattern, and Django takes this static class and transforms it into something capable of runtime interaction — something modular that can be plugged into a web framework.
What does Django do for you?
Let’s step across that domain boundary and brainstorm a list of some of the functionality a Django developer comes to expect “for free” whenever she defines a data model class:
- Explicitly associate (ie. “register”) this newly defined
Studentwith the correct…