Your First Django Model
A Django model is a Python class that stands for one table. A table stores data in rows, and each row holds one item.
Define the model
The Post model stands for one table. It has a title and a body.
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"Make the table
The schema editor makes the table in the database. A real project uses migrations for this step.
from django.db import connection
with connection.schema_editor() as editor:
editor.create_model(Post)Make one post
A post is an object of the model class. The print shows its title.
post = Post(title="First post", body="Hello from Django.")
print(post.title)Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=[
"django.contrib.contenttypes",
"django.contrib.auth",
],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.db import connection, models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
post = Post(title="First post", body="Hello from Django.")
print(post.title)
print(post.body)
Key points
- Each object of the class is one row of the table.
- models.Model is the parent class of every model.
- A CharField holds short text, like a title.
- A TextField holds long text, like a body.
- The Meta class gives the model its app label.
In this example, the setup lines configure Django. The Post class stands for one table with a title and a body. The program creates the table directly. A real project uses migrations for this step. The last lines make one post and print its title and body.
Note
The class describes the table. The table itself is made in the database.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is a Django model?