15 Django Prompts: From Models to REST API — Supercharge Your Backend

Django is one of the most powerful and popular backend frameworks in Python. It is used in Instagram, Pinterest, Disqus, and many other large projects. But even experienced developers often spend hours on routine tasks: writing CRUD operations, configuring serializers, optimizing database queries. What if I told you that with well-crafted prompts for AI assistants, you can cut this time significantly? In this article, I have collected 15 proven prompts that cover all key aspects of working with Django: from creating models to building high-load REST APIs. Each prompt is accompanied by an example usage and explanations so you can adapt it to your tasks.

Basic Prompts: Models and ORM

1. Creating a Model with Fields and Methods

Task: Generate a Django model with the required fields, validation, and methods.

Prompt:

Create a Django model for an online store. Include fields: product name (CharField), price (DecimalField), stock quantity (IntegerField), date added (DateTimeField with auto_now_add). Add a method to calculate the total value of the product in stock and a Meta class with ordering by price.

Example Result:

from django.db import models
from django.core.validators import MinValueValidator

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)])
    stock = models.IntegerField(default=0, validators=[MinValueValidator(0)])
    created_at = models.DateTimeField(auto_now_add=True)

    def total_value(self):
        return self.price * self.stock

    class Meta:
        ordering = ['price']

Explanation: Such a prompt saves time on routine code writing. You can specify field types, add foreign keys, unique constraints, etc.

2. Generating QuerySets with Filtering and Annotation

Task: Write a database query with filtering, aggregation, and annotation.

Prompt:

Write a Django ORM query that returns the top 10 products by total sales (use Sum annotation, ordering, and limit). Models: Order and OrderItem with FK to Product.

Example Result:

from django.db.models import Sum, F

# Assuming OrderItem has quantity field and product FK
top_products = Product.objects.annotate(
    total_sold=Sum('orderitem__quantity')
).order_by('-total_sold')[:10]

Explanation: This prompt allows you to quickly get a complex ORM query without long documentation searches. The key is to clearly describe the model structure.

3. Migrations and Database Schema Management

Task: Generate commands for creating and applying migrations, as well as for rolling back changes.

Prompt:

Describe the process of creating migrations for a new field in a Django model, including the commands makemigrations, migrate, and sqlmigrate for checking SQL.

Example Result:

python manage.py makemigrations
python manage.py migrate
python manage.py sqlmigrate myapp 0001

Explanation: This prompt is useful for beginners who are just getting familiar with migrations. It explains the sequence of actions and the purpose of each command.

Advanced Prompts: Views, API, and Admin

4. Function-Based and Class-Based Views

Task: Create a view to display a list of products with pagination and search.

Prompt:

Write a Django class-based view for a list of products with pagination (20 per page) and search by name. Use ListView and override get_queryset.

Example Result:

from django.views.generic import ListView
from .models import Product

class ProductListView(ListView):
    model = Product
    template_name = 'products/list.html'
    paginate_by = 20

    def get_queryset(self):
        queryset = super().get_queryset()
        query = self.request.GET.get('q')
        if query:
            queryset = queryset.filter(name__icontains=query)
        return queryset

Explanation: Class-based views are the standard in Django. The prompt helps quickly generate them with the desired logic.

5. DRF Serializers and ViewSets

Task: Create a REST API for a model using Django REST Framework.

Prompt:

Create a serializer and ModelViewSet for the Product model. Add filtering by price and search by name. Use DjangoFilterBackend and SearchFilter.

Example Result:

from rest_framework import serializers, viewsets
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'price', 'stock']

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = ['price']
    search_fields = ['name']

Explanation: DRF is the standard for creating APIs in Django. The prompt generates minimal working code that can be extended.

6. Custom Actions in ViewSet

Task: Add a custom action to change the price of a product.

Prompt:

Add a custom @action to ProductViewSet that allows changing the price of a product (POST request with field new_price).

Example Result:

from rest_framework.decorators import action
from rest_framework.response import Response

class ProductViewSet(viewsets.ModelViewSet):
    # ... rest of the code

    @action(detail=True, methods=['post'])
    def change_price(self, request, pk=None):
        product = self.get_object()
        new_price = request.data.get('new_price')
        if new_price is not None:
            product.price = new_price
            product.save()
            return Response({'status': 'ok'})
        return Response({'error': 'new_price required'}, status=400)

Explanation: Custom actions are a powerful feature of DRF. The prompt helps quickly add non-standard operations.

7. Admin Configuration: list_display and Actions

Task: Extend the admin for the Product model: display desired fields, add filters and a custom action.

Prompt:

Create a ProductAdmin class for the Product model. Display fields name, price, stock, created_at in list_display. Add filters by price and date, search by name. Add an action to apply a 10% discount to selected products.

Example Result:

from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'price', 'stock', 'created_at']
    list_filter = ['price', 'created_at']
    search_fields = ['name']
    actions = ['apply_discount_10']

    @admin.action(description='Apply 10% discount')
    def apply_discount_10(self, request, queryset):
        for product in queryset:
            product.price = product.price * 0.9
            product.save()

Explanation: Django admin is a powerful tool, and the prompt allows you to quickly configure it to your needs.

8. Query Optimization: select_related and prefetch_related

Task: Optimize queries with ManyToOne and ManyToMany relationships.

Prompt:

Explain how to use select_related and prefetch_related to reduce the number of database queries. Provide an example for the Order model with FK to User and M2M to Product.

Example Result:

# Instead of N+1 queries
orders = Order.objects.select_related('user').prefetch_related('products')

Explanation: Query optimization is critical for performance. The prompt helps understand how to avoid the N+1 problem.

Expert Prompts: Complex Scenarios

9. Custom Managers and QuerySets

Task: Create a manager with domain-specific methods.

Prompt:

Create a manager for the Product model that adds a method available() for products with stock > 0, and a method cheap(max_price=100) that filters by price below the specified value.

Example Result:

from django.db import models

class ProductQuerySet(models.QuerySet):
    def available(self):
        return self.filter(stock__gt=0)

    def cheap(self, max_price=100):
        return self.filter(price__lt=max_price)

class Product(models.Model):
    # ... fields
    objects = ProductQuerySet.as_manager()

Explanation: Custom managers allow encapsulating frequently used queries.

10. Signals for Business Logic

Task: Create a signal that automatically updates stock when an order is created.

Prompt:

Write a post_save signal for the OrderItem model that decreases the product stock when an order item is created.

Example Result:

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import OrderItem, Product

@receiver(post_save, sender=OrderItem)
def update_stock(sender, instance, created, **kwargs):
    if created:
        product = instance.product
        product.stock -= instance.quantity
        product.save()

Explanation: Signals are a powerful tool for implementing business rules, but they should be used carefully to avoid circular dependencies.

11. Custom Validators and Form Fields

Task: Write a validator for a field that checks the uniqueness of an email domain.

Prompt:

Create a Django validator that checks that the email belongs to the domain @example.com. Use it in the model and form.

Example Result:

from django.core.exceptions import ValidationError

def validate_example_email(value):
    if not value.endswith('@example.com'):
        raise ValidationError('Email must be on the domain example.com')

# In the model:
email = models.EmailField(validators=[validate_example_email])

Explanation: Validators are a key element of data control. The prompt helps implement specific rules.

12. Working with Transactions and Locks

Task: Ensure atomicity of a fund transfer operation.

Prompt:

Write a function that transfers money from one account to another, using transaction.atomic and select_for_update to avoid race conditions.

Example Result:

from django.db import transaction
from .models import Account

def transfer(sender_id, receiver_id, amount):
    with transaction.atomic():
        sender = Account.objects.select_for_update().get(id=sender_id)
        receiver = Account.objects.select_for_update().get(id=receiver_id)
        if sender.balance < amount:
            raise ValueError('Insufficient funds')
        sender.balance -= amount
        receiver.balance += amount
        sender.save()
        receiver.save()

Explanation: Transactions and locks are critical for data integrity. The prompt demonstrates the correct pattern.

13. Testing with pytest-django

Task: Write tests for API endpoints using pytest and DRF.

Prompt:

Write tests for ProductViewSet using pytest-django and APIClient. Check getting the list of products and creating a new product.

Example Result:

import pytest
from rest_framework.test import APIClient
from .models import Product

@pytest.mark.django_db
def test_get_products():
    client = APIClient()
    response = client.get('/api/products/')
    assert response.status_code == 200

@pytest.mark.django_db
def test_create_product():
    client = APIClient()
    data = {'name': 'Test product', 'price': 100, 'stock': 5}
    response = client.post('/api/products/', data, format='json')
    assert response.status_code == 201

Explanation: Automated tests are an integral part of development. The prompt generates basic tests for the API.

14. Caching for Performance Improvement

Task: Explain how to use caching in Django to reduce database load.

Prompt:

Show an example of caching the result of a complex query using cache.set and cache.get, and also how to use cache_page for a view.

Example Result:

from django.core.cache import cache
from .models import Product

def get_top_products():
    key = 'top_products'
    products = cache.get(key)
    if not products:
        products = list(Product.objects.annotate(...).order_by('-total_sold')[:10])
        cache.set(key, products, 300)  # 5 minutes
    return products

# For a view:
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def top_products_view(request):
    # ...

Explanation: Caching is a key tool for scaling. The prompt shows simple and effective methods.

15. Custom Management Commands

Task: Create a management command to clean up outdated records.

Prompt:

Create a custom Django command to delete products with stock = 0 and price less than 100. The command should accept an argument --dry-run to output without deleting.

Example Result:

from django.core.management.base import BaseCommand
from .models import Product

class Command(BaseCommand):
    help = 'Deletes products with zero stock and price below 100'

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true', help='Only show what will be deleted')

    def handle(self, *args, **options):
        products = Product.objects.filter(stock=0, price__lt=100)
        if options['dry_run']:
            self.stdout.write(self.style.WARNING(f'Will be deleted: {products.count()} products'))
        else:
            products.delete()
            self.stdout.write(self.style.SUCCESS('Deleted'))

Explanation: Custom commands automate routine operations and are easy to test.

Conclusion

These 15 prompts are just a small part of what you can do with AI assistants when working with Django. The key is to learn how to formulate tasks correctly: specify the model structure, desired methods, parameters. Then you can generate not just template code, but solutions that exactly match your requirements. Start with simple examples, gradually making requests more complex. And don't forget to check the generated code — even the smartest assistant can make mistakes. Happy coding!

← All posts

Comments