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):
= models.CharField(max_length=100)
my_field = models.IntegerField() my_number
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):
= models.CharField(max_length=100)
my_field
class Meta:
= ['my_field']
ordering = 'My Model'
verbose_name = 'My Models' verbose_name_plural
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):
= models.CharField(max_length=100)
name
class Book(models.Model):
= models.CharField(max_length=100)
title = models.ForeignKey(Author, on_delete=models.CASCADE) author
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):
= models.CharField(max_length=100)
title
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):
= models.CharField(max_length=100)
title = models.BooleanField(default=False)
published
= BookManager() objects
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):
= models.CharField(max_length=100)
name = models.DateTimeField(auto_now_add=True)
created_at
class Meta:
= True
abstract
class Student(CommonInfo):
= models.CharField(max_length=2) grade
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):
= models.CharField(max_length=100)
title = models.DateField()
publication_date
def clean(self):
if self.publication_date > datetime.date.today():
raise ValidationError('Publication date cannot be in the future.')