Models
ORM Usage
Use Django's ORM for defining models and managing database interactions. Each model should represent a single entity or table.
Example:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
Naming Conventions
- Use singular, PascalCase names for models (e.g.,
Invoice,UserProfile). - Use descriptive field names in snake_case.
Relationships
- Use
ForeignKey,ManyToManyField, andOneToOneFieldfor relationships. - Use related_name for reverse relations.
Example:
class Invoice(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invoices')
total = models.DecimalField(max_digits=10, decimal_places=2)
Custom Methods
- Add business logic as model methods or properties.
- Use
@propertyfor computed fields.
Example:
class Invoice(models.Model):
# ...existing fields...
@property
def is_paid(self):
return self.payments.exists()
Advanced ORM Usage
- Use model managers for custom queries.
- Use signals for side effects (e.g., post_save, pre_delete).
Best Practices
- Document model fields and methods with docstrings.
- Use validators for field-level validation.
- Avoid business logic in views; keep it in models or services.
- Write tests for model methods and custom managers.