</>
Skip to content
Django lessons (13/43)

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

FieldDescription
CharFieldShort text
TextFieldLong text
IntegerFieldWhole number
FloatFieldDecimal number
BooleanFieldTrue/False
DateFieldDate
DateTimeFieldDate and time
EmailFieldEmail address
URLFieldURL
ImageFieldImage upload
FileFieldFile upload
ForeignKeyOne-to-many
ManyToManyFieldMany-to-many
OneToOneFieldOne-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

  1. Create a basic model
  2. Add different field types
  3. Create model relationships
  4. 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.