0Pricing
Python Academy · Lesson

Models and Migrations

Define and migrate the database.

Django Models

A Django model is a Python class that defines the structure of a database table. Each attribute is a field. Models live in an app's models.py.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
print('Post model defined')

Field Types

Django provides many field types that map to column types.

  • CharField for short text (needs max_length)
  • TextField for long text
  • IntegerField, BooleanField, DateTimeField
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    views = models.IntegerField(default=0)
print('Fields map to columns')

All lessons in this course

  1. Projects and Apps
  2. Models and Migrations
  3. Views and URLs
  4. The Django Admin
← Back to Python Academy