What are Django Models?

Django models are Python classes that define the structure of your database tables. They use Django's ORM (Object-Relational Mapping) to interact with the database without writing SQL.

Basic Model

Create a simple model:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    
    def __str__(self):
        return self.title

Field Types

Common field types:

class Product(models.Model):
    # Text fields
    name = models.CharField(max_length=100)
    description = models.TextField()
    
    # Numbers
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.IntegerField()
    
    # Boolean
    in_stock = models.BooleanField(default=True)
    
    # Date/Time
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # Foreign Key
    category = models.ForeignKey('Category', on_delete=models.CASCADE)
    
    # Many-to-Many
    tags = models.ManyToManyField('Tag')

Creating Migrations

Create database migrations:

# Create migration files
python manage.py makemigrations

# Apply migrations
python manage.py migrate

Querying Models

Query the database:

# Get all objects
books = Book.objects.all()

# Filter
cheap_books = Book.objects.filter(price__lt=20)

# Get single object
book = Book.objects.get(id=1)

# Create
new_book = Book.objects.create(
    title="Python Guide",
    author="John Doe",
    published_date="2024-01-01",
    price=29.99
)

Relationships

Define relationships:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    
    # Access related objects
    # book.author.name
    # author.book_set.all()

Model Methods

Add custom methods:

class Book(models.Model):
    title = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    
    def apply_discount(self, percent):
        self.price *= (1 - percent / 100)
        self.save()

Best Practices

  • Use descriptive names: Clear model and field names
  • Add __str__ method: For better admin interface
  • Use migrations: Never edit migrations manually
  • Index frequently queried fields: Improve performance

Next Steps

Learn about Django Views to work with models, or explore admin panel for model management.