models.pyIn Django, models define the structure of your database tables. They are Python classes that inherit from django.db.models.Model. Each model represents a table, and each attribute represents a column.
Models are created inside the models.py file of a Django app. You define a class that inherits from models.Model and add fields using Django’s built-in field types.
# Import Django model base class
from django.db import models
# Define a Book model
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publish_date = models.DateField()
isbn_number = models.CharField(max_length=13)
# String representation of the model
def __str__(self):
return self.title
# Product model demonstrating multiple field types
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
# Return product name when printed
def __str__(self):
return self.name
Each model becomes a database table after running migrations. Django automatically generates SQL based on your model definitions.
Step 1: Define your Model Fields
Model ➜ Migration ➜ Database Table
Try modifying a field, run makemigrations, then migrate to see schema updates.
__str__ for readabilityForeignKey