Django — Models
Basic Model
# blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published = models.BooleanField(default=False)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_at']
Field Types
| Field | Description |
|---|---|
| CharField | Short text |
| TextField | Long text |
| IntegerField | Whole number |
| FloatField | Decimal number |
| BooleanField | True/False |
| DateField | Date |
| DateTimeField | Date and time |
| EmailField | Email address |
| URLField | URL |
| ImageField | Image upload |
| FileField | File upload |
| ForeignKey | One-to-many |
| ManyToManyField | Many-to-many |
| OneToOneField | One-to-one |
Field Options
title = models.CharField(
max_length=200,
unique=True,
blank=False,
null=False,
default='Untitled',
verbose_name='Post Title',
help_text='Enter the post title'
)
Relationships
class Author(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
tags = models.ManyToManyField('Tag')
class Tag(models.Model):
name = models.CharField(max_length=50)
Meta Class
class Post(models.Model):
class Meta:
verbose_name = 'Blog Post'
verbose_name_plural = 'Blog Posts'
ordering = ['-created_at']
db_table = 'blog_posts'
Mini Practice
- Create a basic model
- Add different field types
- Create model relationships
- Use the Meta class
Up Next
Continue with Model Fields — field types and options.
Related Topics
Frequently Asked Questions about Models
What is Models in Django?
Models is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Models?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Models.
Why is Models important in Django?
Models is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.