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
models.pyfile inside your project folder (where
urls.pyresides)12345678from django.db import modelsclass 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
PROJECTFOLDERwith your project name. (no trailing slash at the end)
python3 manage.py makemigrations --empty PROJECTFOLDER
python3 manage.py makemigrations
If the above command gives you an error, you’ll need to append the
PROJECTFOLDERto the end of it like so:
python3 manage.py makemigrations PROJECTFOLDER
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.
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.