← Back to Python

All Topics

Advertisement

Learn/Python/Web Development

Django Models

Topic: Django

Advertisement

Introduction

Django ORM provides powerful model definitions and database operations.

Model Definition

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    published_date = models.DateField()

Queries

# All records
Author.objects.all()

# Filter
Author.objects.filter(name__contains="John")

# Get single
author = Author.objects.get(id=1)

# Create
Author.objects.create(name="Alice", email="alice@email.com")

# Update
author.name = "Bob"
author.save()

# Delete
author.delete()

Practice Problems

  1. Create models with relationships
  2. Query with filters and lookups
  3. Use select_related for joins
  4. Implement model methods
  5. Add model validation

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →