Models are a core concept of the Django framework. According to Django’s design philosophies for models, we should be as explicit as possible with the naming and functionality of our fields, and ensure that we’re including all relevant functionality related to our model in the model itself, rather than in the views or somewhere else. If you’ve worked with Ruby on Rails before, these design philosophies won’t seem new as both Rails and Django implement the Active Record pattern for their object-relational mapping (ORM) systems to handle stored data.
In this post we’ll look at some ways to leverage these philosophies, core Django features, and even some libraries to help make our models better.
As a feature of Python since version 2.2, a property’s usage looks like an attribute but is actually a method. While using a property on a model isn’t that advanced, we can use some underutilized features of the Python property to make our models more powerful.
If you’re using Django’s built-in authentication or have customized your authentication using
AbstractBaseUser, you’re probably familiar with the
last_login field defined on the
User model, which is a saved timestamp of the user’s last login to your application. If we want to use
last_login, but also have a field named
last_seen saved to a cache more frequently, we could do so pretty easily.
First, we’ll make a Python property that finds a value in the cache, and if it can’t, it returns the value from the database.
Note: I’ve slimmed the model down a bit as there’s a separate tutorial on this blog about specifically customizing the built-in Django user model.
The property above checks our cache for the user’s
last_seen value, and if it doesn’t find anything, it will return the user’s stored
last_login value from the model. Referencing
<instance>.last_seen now provides a much more customizable attribute on our model behind a very simple interface.
We can expand this to include custom behavior when a value is assigned to our property (
some_user.last_seen = some_date_time), or when a value is deleted from the property (
Now, whenever a value is assigned to our
last_seen property, we save it to the cache, and when a value is removed with
del, we remove it from the cache. Using
deleter is described in the Python documentation but is rarely seen in the wild when looking at Django models.You may have a use case like this one, where you want to store something that doesn’t necessarily need to be persisted to a traditional database, or for performance reasons, shouldn’t be. Using a custom property like the above example is a great solution.
In a similar use case, the
python-social-auth library, a tool for managing user authentication using third-party platforms like GitHub and Twitter, will create and manage updating information in your database based on information from the platform the user logged-in with. In some cases, the information returned won’t match the fields in our database. For example, the
python-social-auth library will pass a
fullname keyword argument when creating the user. If, perhaps in our database, we used
full_name as our attribute name then we might be in a pinch.
A simple way around this is by using the
getter/setter pattern from above:
python-social-auth saves a user’s
fullname to our model (
new_user.fullname = 'Some User'), we’ll intercept it and save it to our database field,
through model relationships
Django’s many-to-many relationships are a great way of handling complex object relationships simply, but they don’t afford us the ability to add custom attributes to the
intermediate models they create. By default, this simply includes an identifier and two foreign key references to join the objects together.
Using the Django
ManyToManyField through parameter, we can create this intermediate model ourselves and add any additional fields we deem necessary.
If our application, for example, not only needed users to have memberships within groups, but wanted to track when that membership started, we could use a custom intermediate model to do so.
In the example above, we’re still using a
ManyToManyField to handle the relationship between a user and a group, but by passing the
Membershipmodel using the
through keyword argument, we can now add our
joinedcustom attribute to the model to track when the group membership was started. This
through model is a standard Django model, it just requires a primary key (we use UUIDs here), and two foreign keys to join the objects together.
Using the same three model pattern, we could create a simple subscription database for our site:
Here we’re able to track when a user first subscribed, when they updated their subscription, and if we added the code paths for it, when a user canceled their subscription to our application.
through models with the
ManyToManyField is a great way to add more data to our intermediate models and provide a more thorough experience for our users without much added work.
Normally in Django, when you subclass a model (this doesn’t include abstract models) into a new class, the framework will create new database tables for that class and link them (via
OneToOneField) to the parent database tables. Django calls this “multi-table inheritance” and it’s a great way to re-use existing model fields and structures and add your own data to them. “Don’t repeat yourself,” as the Django design philosophies state.
Multi-table inheritance example:
This example would create both
vehicles_airplanedatabase tables,linked with foreign keys. This allows us to leverage the existing data that lives inside
vehicles_vehicle, while adding our own vehicle specific attributes to each subclass,
vehicle_airplane, in this case.
In some use cases, we may not need to store extra data at all. Instead, we could change some of the parent model’s behavior, maybe by adding a method, property, or model manager. This is where
proxy models shine.
Proxy models allow us to change the Python behavior of a model withoutchanging the database.
Proxy models are declared just like normal models. In our example, we tell Django that Honda is a
proxy model by setting the
proxy attribute of the Honda
Meta class to
True. I’ve added a property and a method stub example, but you can see we’ve added a custom model manager to our Honda
This ensures that whenever we request objects from the database using our Honda model, we get only
Car instances back where
model= 'Honda'. Proxy models make it easy for us to quickly add customization on top of existing models using the same data. If we were to delete, create, or update any
Car instance using our Honda model or manager, it would be saved into the
vehicles_car database just as if we were using the parent (
If you’re already comfortable working in Python classes, then you’ll feel right at home with Django’s models: inheritance, multiple inheritance, method overrides, and introspection. These models are all part of how the Django object-relational mapper was designed.
Multi-table inheritance and manually defining intermediate tables for SQL joins aren’t necessarily basic concepts, but are implemented simply with a bit of Django and Python knowhow. Being able to leverage features of the language and framework alongside one another is one of the reasons Django is a popular web framework.
For further reading, check out Django’s documentation topic for models.