Introduction
Models let you organize and save data in your app. Fields define what kind of data each part holds.
Models let you organize and save data in your app. Fields define what kind of data each part holds.
from django.db import models class ModelName(models.Model): field_name = models.FieldType(options)
Each field represents a column in the database.
FieldType can be CharField, IntegerField, DateTimeField, etc.
class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField()
class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() published = models.DateTimeField()
class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2)
This model defines a Book with title, author, and year. The __str__ method shows a friendly name.
from django.db import models class Book(models.Model): title = models.CharField(max_length=150) author = models.CharField(max_length=100) published_year = models.IntegerField() def __str__(self): return f"{self.title} by {self.author} ({self.published_year})"
Always set max_length for CharField to limit text size.
Use appropriate field types to match the data you want to store.
After defining models, run migrations to create database tables.
Models organize data with fields as columns.
Each field type controls what data is saved.
Define models before saving or querying data.
title with a maximum length of 100 in a Django model?CharField with max_length is correct.TextField does not use max_length, IntegerField is for numbers, and CharField requires max_length, not length.is_active field for a new instance if not specified?
class User(models.Model):
username = models.CharField(max_length=50)
is_active = models.BooleanField(default=true)
True and False (capitalized). true is undefined.default=true raises NameError at model definition time, preventing instance creation.class Product(models.Model):
price = models.DecimalField(max_digits=5, decimal_places=2, max_length=10)
max_digits and decimal_places, but not max_length.max_length causes a syntax error because it's invalid for DecimalField.BlogPost with a title (max 200 chars), content (unlimited text), and a published date that can be empty. Which of the following is the best model definition?CharField(max_length=200) is correct. Content is unlimited text, so TextField fits.blank=True and null=True on DateTimeField.Pass the test and this pattern moves unknown