Django Models Migrations

This post will be a simple Django models “getting started” guide. I will be using Django 1.8.x and Python 3. I will assume you have already configured Django to use a database in settings.py.

  1. Create a models.py file inside your project folder (where urls.py resides)

    1
    2
    3
    4
    5
    6
    7
    8
    from django.db import models
    class User(models.Model):
    username = models.CharField(max_length=32, unique=True)
    password = models.CharField(max_length=256)
    class Meta:
    db_table = 'users'

    This is just a basic “user” model to get you started.

  2. Next, create the empty migration data. Make sure you replace PROJECTFOLDER with your project name. (no trailing slash at the end)

    python3 manage.py makemigrations --empty PROJECTFOLDER

  3. Make migrations

    python3 manage.py makemigrations

    If the above command gives you an error, you’ll need to append the PROJECTFOLDER to the end of it like so:

    python3 manage.py makemigrations PROJECTFOLDER

  4. Migrate

    python3 manage.py migrate

  5. Start your project

    python3 manage.py runserver

If everything worked, the server should start and not give any errors.

Any changes you make to models.py will need to be re-synced with the database. This means you need to run steps 3 and 4 to merge the changes into the database.


Basic Usage

So now that you have models working, you will want to be able to query the data. Django makes this very easy to do and you do not need to worry about SQL injections.

user = User.objects.get(username='test_user')

If a row with the username field as ‘test_user’ is found it will return a User class object. If not, it will throw an exception.

Modifying a row is easy too.

1
2
u.username = 'new_user_name'
u.save()