Menu
CoddyTech

Your First Model

Part of the Models and the Admin section of Coddy's Django journey. Lesson 1 of 23.

Your bookshelf site has to remember books, and a view forgets everything once it answers. Sites keep data in a database: tables where each row is one record. In Django you describe the data with a model, a class in an app's models.py, and Django builds the table. Each field becomes a column:

from django.db import models


class Movie(models.Model):
    title = models.CharField(max_length=150)
    director = models.CharField(max_length=80)

CharField holds short text, at most max_length characters. Django adds an id column on its own, a number that tells the rows apart.

The class alone creates no table. python manage.py makemigrations writes a migration, a file in the app's migrations/ folder that describes the change, and python manage.py migrate applies it to the database. The Run button runs both.

challenge icon

Challenge

Easy

In books/models.py, write a model Book with two short text fields:

  • title, at most 200 characters
  • author, at most 100 characters

Press Run. The Console shows makemigrations writing books/migrations/0001_initial.py and migrate applying it. The Data tab shows the new, empty books.Book table.

Try it yourself

from django.db import models

# Create your models here.

All lessons in Models and the Admin

Practice on your own: Django playground