Django Model Definitions: How They Differ From the Generated Database Schema

Adrienne Domingus
7 min readJul 10, 2020

Models are the way we tell Django what we want our database schema to look like, and are the things through which we interact with rows, or instances, in our database.

One of the benefits of using a framework like Django is that it provides functionality making it easier to create and interact with our data than if we had to do so directly with the database and generate and validate our own SQL statements. This means that there are things that will look different in the database than they do in our code — this is okay! But it’s also interesting to look at some of them to better understand where Postgres (in this example, you may be using a different database engine) and Django diverge, and which is driving what behavior.

Let’s build an example model as we go through this, so that at the end we can take a comprehensive look at the differences between our model definition, the migration file, and the database schema.

from django.db import modelsclass BlogPost(models.Model):
# We'll build out our model definition here!

Primary Keys

By default, models are given an id field as the primary key without needing to define it at all (so nothing to add to our example model definition we’ll be using throughout this post!) — documented here.

Foreign Keys

To our example Post class, we’ll add a foreign key to the author:

author = models.ForeignKey(User)

However, what’s actually stored in the database for foreign keys is the value of the related object’s primary key (typically the id field, as mentioned above). For this reason, the name of the field in the database will be slightly different than our model definition: the field will be author_id. Both author and author_id are available as properties on a model instance.

Optimization note: there’s a cool implication of this! Because of Django magic related to defining something as a ForeignKey (instead of just an integer, which is what’s actually stored as the database), when we call .author on an instance of a blog post, it will retrieve that instance from the database as well. If all we…

Recommended from Medium


See more recommendations