Django Models Migrations
Nov 2, 2015
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
.
-
Create a
models.py
file inside your project folder (whereurls.py
resides)``` 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.
-
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
-
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
-
Migrate
python3 manage.py migrate
-
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.
u.username = 'new_user_name'
u.save()