Django models and working with the database
In the previous lesson we made our first Django project and started a local web server.
Now we will learn how Django uses a database to store information.
What is the Django ORM?
The ORM lets us work with the database using Python code instead of SQL commands.
- tables in the database → Python classes
- columns in a table → class attributes
- rows in a table → objects of the class
What is a model in Django?
A model is a Python class that describes the structure of the data in the database.
A model is defined in the file models.py.
An example model
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
This model creates a table in the database with three columns:
- title
- text
- date (filled in automatically when the post is created)
Database migrations
After the model is defined, the database has to be updated.
This is done with Django migrations.
python manage.py makemigrations
python manage.py migrate
Adding data to the database
We can add data from the Django shell.
python manage.py shell
from blog.models import Post
post = Post(title="First post", text="Test text")
post.save()
This code adds a new row to the database table.
Viewing the data
Post.objects.all()
This command returns all the records from the table.
The Django admin panel
One of the biggest advantages of the Django framework is its built-in administration panel.
It makes it easy to manage the data in the database.
python manage.py createsuperuser
After that we can open the admin panel:
http://127.0.0.1:8000/admin
Related tutorials
If you want to see how a Django application is later put on a real web server, see the following tutorials:
- Creating a Django web application – starting the project
- Deploying a Django application to the Heroku platform (SR)
Frequently asked questions
What is a Django model?
A model is a Python class that defines the structure of the data in the database.
What does the Django ORM do?
The ORM lets you work with the database without writing SQL queries.
What are migrations?
Migrations update the structure of the database according to the defined models.
What is Django admin?
The admin panel lets you manage the application data through a web interface.
