Expert guidance on Django ORM models, fields, relationships, querysets, and migrations from official Django documentation
Expert guidance on Django ORM models based on the official Django 5.1 documentation. This skill helps you define models, work with fields, establish relationships, and manage database schemas using Django's powerful ORM.
This skill provides comprehensive knowledge about Django models, including:
When the user asks about Django models, follow these steps:
1. **Understand the Question**
- Identify what aspect of Django models the user is asking about (fields, relationships, queries, migrations, etc.)
- Determine if they need help with model definition, querying, or schema changes
- Note any specific Django version requirements (default to Django 5.1 patterns)
2. **Provide Model Structure Guidance**
- Show proper model class definition inheriting from `django.db.models.Model`
- Explain field types and their appropriate use cases
- Demonstrate field options (`null`, `blank`, `default`, `choices`, etc.)
- Include verbose names and help text for clarity
3. **Explain Relationships**
- For many-to-one: Use `ForeignKey` with appropriate `on_delete` behavior
- For many-to-many: Use `ManyToManyField` with optional `through` models
- For one-to-one: Use `OneToOneField` for extending models
- Show both forward and backward relationship access patterns
4. **Cover Field Options**
- Explain common options: `null`, `blank`, `default`, `db_default`, `choices`, `unique`, `primary_key`
- Show how to use enumeration classes for choices (Django 5.0+)
- Demonstrate custom validation and help text
- Explain the difference between `null` (database) and `blank` (validation)
5. **QuerySet and Database Access**
- Show basic query patterns: `.all()`, `.filter()`, `.get()`, `.exclude()`
- Explain query chaining and lazy evaluation
- Demonstrate complex queries with `Q` objects and lookups
- Show aggregation and annotation patterns
6. **Migrations Best Practices**
- Explain when to run `makemigrations` vs `migrate`
- Show how to handle model changes safely
- Demonstrate data migrations when needed
- Explain migration dependencies and ordering
7. **Meta Options and Methods**
- Show common Meta options: `ordering`, `verbose_name`, `db_table`, `indexes`, `constraints`
- Demonstrate useful model methods: `__str__()`, `get_absolute_url()`, custom managers
- Explain when to use `@property` vs database fields
8. **Code Examples**
- Provide complete, working examples based on Django 5.1 syntax
- Show imports from `django.db import models`
- Include docstrings and comments for clarity
- Demonstrate both simple and complex use cases
9. **Common Patterns**
- Abstract base models for shared fields
- Custom managers and QuerySets
- Model inheritance (abstract, multi-table, proxy)
- Signals for model lifecycle hooks
- Validation with `clean()` method
10. **Best Practices**
- Use appropriate field types for data
- Set `on_delete` explicitly for ForeignKey fields
- Use `related_name` for reverse relationships
- Avoid field names that conflict with model API (`save`, `delete`, `clean`)
- Keep models focused and use composition over complex inheritance
**User asks:** "How do I create a Django model for blog posts with categories?"
**Response should include:**
```python
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
class Meta:
verbose_name_plural = "categories"
ordering = ['name']
def __str__(self):
return self.name
class BlogPost(models.Model):
STATUS_CHOICES = {
'draft': 'Draft',
'published': 'Published',
'archived': 'Archived',
}
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='posts')
content = models.TextField()
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
indexes = [
models.Index(fields=['-created_at']),
models.Index(fields=['status', '-created_at']),
]
def __str__(self):
return self.title
```
Then explain: field choices, relationships with appropriate `on_delete`, Meta options, and how to query these models.
Based on official Django 5.1 documentation: https://docs.djangoproject.com/en/5.1/topics/db/models/
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/django-models-expert/raw