Django is one of the most powerful and popular backend frameworks in Python. But even experienced developers spend hours on routine tasks: writing models, serializers, views. What if a neural network could take over some of this work? I've collected 15 prompts that will speed up your Django development—from model design to API optimization. No magic, just proven techniques and code examples.
Basic Prompts: Models and Migrations
1. Designing a Model from a Description
Prompt:
"Create a Django model for [entity] with fields: [list fields and types]. Add str, Meta, indexes, and relationships with other models."
Example:
"Create a Django model for a blog with fields: title (string), content (text), author (ForeignKey to User), created_at (date), published (boolean). Add str, Meta, indexes, and a relationship with comments."
Result:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
published = models.BooleanField(default=False)
class Meta:
indexes = [
models.Index(fields=['created_at']),
]
ordering = ['-created_at']
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
Why it works: The neural network understands standard Django ORM patterns and generates code that conforms to the official documentation docs.djangoproject.com.
2. Generating Migrations from Model Changes
Prompt:
"Generate a Django migration for adding field [field] to model [model]. Consider that the field must have a default value for existing records."
Example:
"Generate a Django migration for adding the field is_active (BooleanField, default=True) to the model UserProfile."
Result:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='is_active',
field=models.BooleanField(default=True),
),
]
Tip: After generation, be sure to run python manage.py makemigrations and migrate to apply the changes to the actual database.
3. Writing Complex ORM Queries
Prompt:
"Write a Django ORM query for [task]. Use aggregations, annotations, and optimization with select_related/prefetch_related."
Example:
"Write a Django ORM query to get the top 5 authors by number of posts in the last month."
Result:
from django.db.models import Count, Q
from datetime import timedelta
from django.utils import timezone
month_ago = timezone.now() - timedelta(days=30)
top_authors = User.objects.filter(
posts__created_at__gte=month_ago
).annotate(
post_count=Count('posts')
).order_by('-post_count')[:5]
Advanced Prompts: Views and Serializers
4. Class-Based Views with Mixins
Prompt:
"Create a Django view for [entity] using generics or mixins. Support CRUD operations."
Example:
"Create ListView and DetailView for the Post model with pagination."
Result:
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
model = Post
template_name = 'blog/post_list.html'
context_object_name = 'posts'
paginate_by = 10
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
5. DRF Serializer with Validation
Prompt:
"Write a Django REST Framework serializer for model [model]. Add field validation and custom methods."
Example:
"Write a DRF serializer for the Post model with validation for title length and an author_name field (read-only)."
Result:
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(source='author.username', read_only=True)
class Meta:
model = Post
fields = ['id', 'title', 'content', 'author_name', 'created_at', 'published']
def validate_title(self, value):
if len(value) < 5:
raise serializers.ValidationError("Title must be at least 5 characters long.")
return value
6. ViewSet with Custom Actions
Prompt:
"Create a ViewSet for model [model] and add a custom action [action]."
Example:
"Create a ViewSet for the Post model and add a publish action that sets published=True."
Result:
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Post
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
@action(detail=True, methods=['post'])
def publish(self, request, pk=None):
post = self.get_object()
post.published = True
post.save()
return Response({'status': 'published'}, status=status.HTTP_200_OK)
Expert Prompts: API, Optimization, and Security
7. Optimizing Queries with select_related
Prompt:
"Optimize a Django query that causes the N+1 problem. Use select_related and prefetch_related."
Example:
"Optimize a query that outputs a list of posts with authors and comments."
Result:
posts = Post.objects.select_related('author').prefetch_related('comments')
8. Custom Authentication in DRF
Prompt:
"Implement JWT authentication in Django REST Framework. Describe the setup in settings.py and usage."
Result:
Install djangorestframework-simplejwt and add to settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
Then add URLs in urls.py:
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view()),
path('api/token/refresh/', TokenRefreshView.as_view()),
]
9. Pagination and Filtering in DRF
Prompt:
"Set up pagination and filtering for an API on Django REST Framework. Use django-filter."
Result:
In settings.py:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
}
In views.py:
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['author', 'published']
10. Caching for High-Load APIs
Prompt:
"Add caching in Django REST Framework for GET requests. Use cache_page or low-level caching."
Example:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.views import APIView
from rest_framework.response import Response
class PostListAPIView(APIView):
@method_decorator(cache_page(60 * 15))
def get(self, request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
11. Security: Protection Against SQL Injection and XSS
Prompt:
"Check Django code for vulnerabilities and suggest fixes. Use safe ORM methods and escaping."
Result:
Use ORM instead of raw SQL:
# Dangerous (raw SQL)
cursor.execute("SELECT * FROM auth_user WHERE username = '%s'" % username)
# Safe (ORM)
User.objects.filter(username=username)
To protect against XSS in templates, use {{ value|escape }} — Django does this automatically.
12. Documenting API with OpenAPI
Prompt:
"Generate an OpenAPI schema for a Django REST Framework project. Describe the setup and usage."
Result:
Install drf-spectacular and add to settings.py:
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
In urls.py:
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
urlpatterns = [
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='docs'),
]
13. Background Tasks with Celery
Prompt:
"Integrate Celery into Django to perform background tasks. Write an example task."
Result:
Install celery and create myapp/tasks.py:
from celery import shared_task
@shared_task
def send_welcome_email(user_id):
from .models import User
user = User.objects.get(id=user_id)
# sending logic
In settings.py:
CELERY_BROKER_URL = 'redis://localhost:6379/0'
14. Debugging and Profiling Django Applications
Prompt:
"Describe methods for debugging a Django application, including Django Debug Toolbar and query profiling."
Result:
Install django-debug-toolbar and add to settings.py:
INSTALLED_APPS = ['debug_toolbar', ...]
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware', ...]
INTERNAL_IPS = ['127.0.0.1']
For profiling, use django-silk or the built-in cProfile.
15. Migrating to Django 5
Prompt:
"Create a migration plan from Django 4 to Django 5. List the main changes and potential issues."
Result:
According to the official migration guide docs.djangoproject.com, key changes include:
- Support for Python 3.10+;
- New ORM features (e.g., Q objects with |);
- Deprecated functions such as django.utils.timezone.utc (use datetime.timezone.utc).
Summary
These 15 prompts cover 90% of routine tasks for a Django developer. Use them as a starting point, but always review the generated code and adapt it to your project. Neural networks are great assistants, but the responsibility for code quality lies with you. Subscribe to our blog to get more practical materials on Python and Django!
Comments