Creating Objects in Django
Creating an object saves a new row in the database. The objects manager builds the row from the given values.
Save one post
Create takes the title and the body. The saved post is kept in a variable.
post = Post.objects.create(title="First post", body="Hello from Django.")
print(post.title)Count the rows
Count shows how many posts are saved. One create call means one row.
print(Post.objects.count())Save a second post
A second create call adds a second row. Count grows to two.
Post.objects.create(title="Second post", body="Models save rows.")
print(Post.objects.count())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.objects.create(title="First post", body="Hello from Django.")
Post.objects.create(title="Second post", body="Models save rows.")
print(Post.objects.count())
for post in Post.objects.all().order_by("title"):
print(post.title)
Key points
- Post.objects is the manager that talks to the Post table.
- Use Post.objects.create() to save a new post.
- Create takes each field value as a keyword argument, like title="First post".
- Create saves the row at once, so no extra save call is needed.
- Use Post.objects.count() to count the saved rows.
In this example, the setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. Two create calls save two posts. Count prints 2. The loop reads every post with .all() and prints each title in title order.
Note
Create returns the saved object, so it can be kept in a variable.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Post.objects.create() do?