Model Design

Model Design

Basic Model Definition

Django models are defined as Python classes that inherit from django.db.models.Model. Each attribute of the class represents a database field.

from django.db import models

class MyModel(models.Model):
    my_field = models.CharField(max_length=100)
    my_number = models.IntegerField()

Field Types

Django provides a wide range of field types to represent different data types:

  • CharField for short text.
  • TextField for large text.
  • IntegerField for integers.
  • FloatField for floating-point numbers.
  • BooleanField for boolean values.
  • DateField and DateTimeField for dates and timestamps.
  • ForeignKey, OneToOneField, ManyToManyField for relationships between models.

Meta Options

Meta options are used to define model-level metadata, such as ordering, verbose names, and database table names.

class MyModel(models.Model):
    my_field = models.CharField(max_length=100)

    class Meta:
        ordering = ['my_field']
        verbose_name = 'My Model'
        verbose_name_plural = 'My Models'

Model Relationships

Django ORM supports three types of relationships: - One-to-One (OneToOneField): Each instance of a model is related to one instance of another model. - Many-to-One (ForeignKey): Many instances of a model are related to one instance of another model. - Many-to-Many (ManyToManyField): Many instances of a model are related to many instances of another model.

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

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

Field Options

Field options allow you to specify constraints and attributes for model fields.

  • max_length: Maximum length of the field (for CharField and TextField).
  • default: Default value for the field.
  • null: If True, Django will store empty values as NULL in the database.
  • blank: If True, the field is allowed to be blank.
  • choices: A list of valid choices for this field.
  • unique: If True, this field must be unique throughout the table.

Model Methods

You can add methods to your model to encapsulate business logic or utility functions.

class Book(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return f"/books/{self.id}/"

Custom Managers and QuerySets

Custom managers and querysets allow you to define reusable query logic.

class BookManager(models.Manager):
    def published(self):
        return self.filter(published=True)

class Book(models.Model):
    title = models.CharField(max_length=100)
    published = models.BooleanField(default=False)

    objects = BookManager()

Model Inheritance

Django supports model inheritance, allowing you to reuse common fields and methods.

  • Abstract Base Classes: Used when you want to put some common information into a base class.
  • Multi-table Inheritance: Each model in the hierarchy gets its own database table.
  • Proxy Models: Used to modify the Python-level behavior without changing the model’s fields.
class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

class Student(CommonInfo):
    grade = models.CharField(max_length=2)

Signals

Signals allow decoupled applications to get notified when certain actions occur (e.g., a model instance is saved or deleted).

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Book)
def book_saved(sender, instance, **kwargs):
    print(f"Book saved: {instance.title}")

Model Validations

You can define custom validation logic within your model.

class Book(models.Model):
    title = models.CharField(max_length=100)
    publication_date = models.DateField()

    def clean(self):
        if self.publication_date > datetime.date.today():
            raise ValidationError('Publication date cannot be in the future.')
Back to top