Skip to content

Django Services, Selectors & Serializers — The Business Logic Layer

This document describes the production architecture of the Django business layer: where logic lives, who reads data, who writes it, and how HTTP never leaks into the domain.


Section What's inside
Architecture map Where each layer lives
Serializers InputSerializer, OutputSerializer, validate()
Services Stateless functions, transactions, side effects
Selectors CQRS-light, N+1, query abstraction
Full data flow HTTP → View → Serializer → Service → Selector → DB
Anti-patterns What not to do and why
Responsibility table Who does / doesn't do what

Architecture map

HTTP Request
    │
    ▼
┌─────────────────────────────┐
│  View (views.py)            │  ← Thin HTTP orchestrator
│  Receives the request       │
│  Calls the serializer       │
│  Passes data to the Service │
│  Returns a Response         │
└────────────┬────────────────┘
             │
             ▼
┌─────────────────────────────┐
│  InputSerializer            │  ← Validation + transformation
│  (serializers.py)           │     of input data
└────────────┬────────────────┘
             │ validated_data
             ▼
┌─────────────────────────────┐
│  Service (services.py)      │  ← Business logic + transaction
│  Orchestrates operations    │     + side effects
│  Knows nothing about HTTP   │
│  Calls the Selector         │
└────────────┬────────────────┘
             │
     ┌───────┴───────┐
     │               │
     ▼               ▼
┌──────────┐   ┌──────────────────────┐
│ Selector │   │  Infrastructure      │
│(selectors│   │  (email, S3, Celery) │
│  .py)    │   └──────────────────────┘
│  Reading │
│  data    │
└────┬─────┘
     │
     ▼
┌─────────────────────────────┐
│  ORM (models.py)            │  ← DB schema, relationships
└────────────┬────────────────┘
             │
             ▼
         PostgreSQL
             │
             ▼
┌─────────────────────────────┐
│  OutputSerializer           │  ← Response formatting
│  (serializers.py)           │
└────────────┬────────────────┘
             │
             ▼
         HTTP Response

Serializers — Transport Layer

The core principle

A serializer is the boundary between HTTP and the domain. It knows nothing about business logic. It only: - takes raw HTTP data → validates it → returns validated_data - takes domain objects → formats them → returns JSON

Anti-pattern: ModelSerializer as the single entry point

# BAD — ModelSerializer tightly couples HTTP to the DB schema
class FloodEventSerializer(serializers.ModelSerializer):
    class Meta:
        model = FloodEvent
        fields = '__all__'

The problem: a change in the model → a change in the API. Business rules end up in save(). There is no explicit contract.

The right way: InputSerializer + OutputSerializer

# serializers.py

class FloodEventInputSerializer(serializers.Serializer):
    """Input data contract — independent of the model."""
    region_name = serializers.CharField(max_length=200)
    severity_level = serializers.ChoiceField(choices=['low', 'medium', 'high'])
    detected_at = serializers.DateTimeField()


class FloodEventOutputSerializer(serializers.Serializer):
    """Output data contract — what the client sees in the response."""
    id = serializers.IntegerField()
    region_name = serializers.CharField()
    severity_level = serializers.CharField()
    detected_at = serializers.DateTimeField()
    created_by_email = serializers.EmailField(source='created_by.email')

The validate() method — Intercepting before validated_data

validate(self, data) is the hook for cross-field validation and transformation.

class FloodEventInputSerializer(serializers.Serializer):
    region_name = serializers.CharField()
    # slug is generated by the server — read_only so DRF doesn't require it in the request
    slug = serializers.SlugField(read_only=True)

    def validate(self, data: dict) -> dict:
        # Auto-generate a field before validated_data
        data['slug'] = slugify(data['region_name'])
        return data

Important: server-generated fields must be declared with read_only=True (a plain Serializer has no Meta; Meta.read_only_fields is a ModelSerializer option), otherwise the serializer will fail validation before validate() is even called.

Complex serialization — A pure Python function

When the response structure is too complex for an OutputSerializer:

# selectors.py or a separate module

def flood_feed_serialize(events: list) -> list[dict]:
    """
    Works around OutputSerializer limitations for complex joined structures.
    Builds the response in Python after an optimized SQL query.
    """
    region_cache = {}  # in-memory cache for repeated values

    result = []
    for event in events:
        region_id = event.region_id
        if region_id not in region_cache:
            region_cache[region_id] = event.region.display_name

        result.append({
            'id': event.id,
            'region': region_cache[region_id],
            'severity': event.severity_level,
            'detected_at': event.detected_at.isoformat(),
        })
    return result

The benefit: full control over the SQL footprint, no N+1 from nested serializers.


Mapping domain errors → HTTP

Domain code raises django.core.exceptions.ValidationError. DRF expects rest_framework.exceptions.ValidationError.

The solution is a custom exception handler:

# shared/exceptions/handlers.py

from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.serializers import as_serializer_error


def custom_exception_handler(exc, context):
    if isinstance(exc, DjangoValidationError):
        exc = DRFValidationError(detail=as_serializer_error(exc))

    return exception_handler(exc, context)
# settings.py
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'shared.exceptions.handlers.custom_exception_handler',
}

Services — Business logic layer

The principle

A Service is a transport-agnostic business function. It knows nothing about HTTP, does not return a Response, and does not import DRF. The same Service is called from:

  • a REST API View
  • a Celery Task
  • a Django Management Command
  • a WebSocket consumer
  • a Pytest test

Anatomy of a stateless service

# apps/flood/services.py

from django.db import transaction
from apps.flood.models import FloodEvent
from apps.flood.tasks import notify_emergency_services_task


@transaction.atomic
def flood_event_create(
    *,                              # keyword-only — protects against argument-order mistakes
    region_name: str,
    severity_level: str,
    detected_at,
    created_by,
) -> FloodEvent:
    """
    The single place where FloodEvent creation logic lives.
    Does not return a Response — returns a domain object.
    """
    event = FloodEvent(
        region_name=region_name,
        severity_level=severity_level,
        detected_at=detected_at,
        created_by=created_by,
    )
    event.full_clean()   # Django validation at the domain level
    event.save()

    # Side effect — only after a successful commit
    transaction.on_commit(
        lambda: notify_emergency_services_task.delay(event.id)
    )

    return event

The * before the arguments is Python syntax for keyword-only parameters. flood_event_create(region_name="Kyiv", severity_level="high", ...) — explicit and safe during refactoring.

Transactions and Side Effects

A critical rule: side effects (email, Celery task) run only after a successful commit.

# apps/flood/services.py

@transaction.atomic
def flood_event_complete_processing(*, event: FloodEvent) -> FloodEvent:
    # 1. DB mutation
    event.status = 'processed'
    event.save(update_fields=['status'])

    # 2. Side effect — runs ONLY if the transaction closed without an error
    transaction.on_commit(
        lambda: notify_emergency_services_task.delay(event.id)
    )

    return event

If you write notify_emergency_services_task.delay(event.id) without on_commit, Celery may receive the task before the record appears in the DB.

A Celery Task is also a transport layer

# apps/flood/tasks.py

@shared_task
def notify_emergency_services_task(event_id: int):
    """A task is a delivery queue, not a place for logic."""
    from apps.flood.selectors import flood_event_get_by_id
    from apps.flood.services import flood_event_notify

    event = flood_event_get_by_id(event_id=event_id)
    flood_event_notify(event=event)   # the logic lives in the service

Full example: View + Service

# apps/flood/views.py

class FloodEventCreateAPIView(APIView):

    def post(self, request):
        serializer = FloodEventInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        event = flood_event_create(
            **serializer.validated_data,
            created_by=request.user,
        )

        output = FloodEventOutputSerializer(event)
        return Response(output.data, status=status.HTTP_201_CREATED)

View: 6 lines. All the logic is in the service.


Selectors — Data reading layer

The principle (CQRS-light)

The architecture distinguishes two fundamentally different operations:

Services Selectors
What they do Mutate data, orchestrate business operations Read data
Operation types CREATE, UPDATE, DELETE, side effects SELECT
Transactions @transaction.atomic No
Scaling under load Vertical scaling Horizontal (read replicas)

Why not a model property?

# BAD — a hidden query inside a Python loop → N+1
class FloodEvent(models.Model):
    @property
    def region_display(self):
        return self.region.display_name  # a SELECT every time in the loop
# GOOD — an optimized query in a selector
def flood_events_get_list(*, user) -> QuerySet:
    return (
        FloodEvent.objects
        .filter(created_by=user)
        .select_related('region')      # one JOIN instead of N queries
        .prefetch_related('tags')      # batched prefetch for M2M
        .annotate(
            comment_count=Count('comments')
        )
        .order_by('-detected_at')
    )

Anatomy of a selector

# apps/flood/selectors.py

def flood_event_get_by_id(*, event_id: int) -> FloodEvent:
    """Basic selector — returns the object or raises FloodEvent.DoesNotExist (the View turns it into a 404)."""
    try:
        return FloodEvent.objects.get(id=event_id)
    except FloodEvent.DoesNotExist:
        raise FloodEvent.DoesNotExist(f"FloodEvent {event_id} не знайдено")


def flood_events_get_visible_for(*, user) -> QuerySet:
    """
    Hides SQL details behind a domain name.
    Returns a QuerySet — the View can add pagination or filtering.
    """
    return (
        FloodEvent.objects
        .filter(
            Q(created_by=user) | Q(is_public=True)
        )
        .select_related('region', 'created_by')
        .order_by('-detected_at')
    )

QuerySet vs evaluated list

Selectors can return:

Returns When to use
QuerySet The View can add .filter(), pagination, django_filters
list[dict] When complex Python optimization is needed before returning
# A selector that returns a QuerySet — the View adds pagination
def flood_events_get_list() -> QuerySet:
    return FloodEvent.objects.all().select_related('region')

# In the View:
queryset = flood_events_get_list()
page = self.paginate_queryset(queryset)   # DRF pagination — safe

Selector + django-filter without leaking the ORM into the View

# apps/flood/filters.py

import django_filters
from apps.flood.models import FloodEvent

class FloodEventFilter(django_filters.FilterSet):
    severity = django_filters.ChoiceFilter(choices=FloodEvent.SEVERITY_CHOICES)
    after = django_filters.DateTimeFilter(field_name='detected_at', lookup_expr='gte')

    class Meta:
        model = FloodEvent
        fields = ['severity', 'after']
# apps/flood/views.py

class FloodEventListAPIView(ListAPIView):

    def get_queryset(self):
        qs = flood_events_get_visible_for(user=self.request.user)  # selector
        return FloodEventFilter(self.request.GET, queryset=qs).qs  # filtering

The View doesn't know SQL. The Selector doesn't know the request filters. The Filter doesn't know the business rules.


Full Data Flow

┌────────────────────────────────────────────────────────────────┐
│ 1. HTTP POST /api/flood/events/                                │
│    body: {"region_name": "Kyiv", "severity_level": "high"}    │
└───────────────────────┬────────────────────────────────────────┘
                        │
                        ▼
┌────────────────────────────────────────────────────────────────┐
│ 2. FloodEventCreateAPIView.post()                              │
│    Thin View — HTTP orchestration only                         │
└───────────────────────┬────────────────────────────────────────┘
                        │
                        ▼
┌────────────────────────────────────────────────────────────────┐
│ 3. FloodEventInputSerializer(data=request.data)                │
│    .is_valid(raise_exception=True)                             │
│    → validated_data = {"region_name": "Kyiv", ...}            │
└───────────────────────┬────────────────────────────────────────┘
                        │ validated_data
                        ▼
┌────────────────────────────────────────────────────────────────┐
│ 4. flood_event_create(**validated_data, created_by=user)       │
│    @transaction.atomic                                         │
│    event.full_clean() → event.save()                           │
│    transaction.on_commit(→ Celery task)                        │
│    return FloodEvent instance                                  │
└───────────────────────┬────────────────────────────────────────┘
                        │ FloodEvent object
                        ▼
┌────────────────────────────────────────────────────────────────┐
│ 5. FloodEventOutputSerializer(event)                           │
│    Formats the domain object as JSON                           │
└───────────────────────┬────────────────────────────────────────┘
                        │
                        ▼
┌────────────────────────────────────────────────────────────────┐
│ 6. Response(output.data, status=201)                           │
└────────────────────────────────────────────────────────────────┘

Anti-patterns

Business logic in serializer.save()

# BAD
class FloodEventSerializer(serializers.ModelSerializer):
    def save(self):
        self.instance.notify_emergency_services()  # business logic in the serializer
        super().save()
# GOOD
# View → Service → a separate notification call
event = flood_event_create(**validated_data)
flood_event_notify(event=event)

HTTP objects in a service

# BAD
def process_flood(request):
    user = request.user       # the Service knows about the HTTP request
    data = request.data
# GOOD
def flood_event_create(*, region_name: str, created_by):
    pass   # the Service receives already-parsed data

ORM in the View

# BAD
class FloodListView(APIView):
    def get(self, request):
        events = FloodEvent.objects.filter(
            created_by=request.user
        ).select_related('region')   # ORM directly in the View
# GOOD
class FloodListView(APIView):
    def get(self, request):
        events = flood_events_get_visible_for(user=request.user)  # Selector

Business logic in a Celery task

# BAD
@shared_task
def process_flood_task(event_id):
    event = FloodEvent.objects.get(id=event_id)
    event.status = 'processed'
    event.save()
    send_email(event.created_by.email, ...)   # logic directly in the task
# GOOD
@shared_task
def process_flood_task(event_id):
    event = flood_event_get_by_id(event_id=event_id)
    flood_event_complete_processing(event=event)   # delegation to the service

Responsibility table

Layer Should Should NOT
View Handle HTTP, call the serializer and the service, return a Response Know SQL, contain business logic, make ORM queries
InputSerializer Validate types and formats, transform data, return validated_data Save to the DB, contain business rules
OutputSerializer Format a domain object into a JSON structure Query the DB, contain logic
Service Orchestrate business operations, open transactions, trigger side effects Know HTTP, import DRF, return a Response
Selector Read data from the DB, optimize queries (select_related, annotate) Mutate data, contain business logic
ORM / Model Describe the DB schema and relationships Contain business orchestration, know HTTP
Celery Task Transport the call into the queue, delegate to the service Contain business logic

File structure in an app

apps/flood/
    ├── models.py          ← DB schema
    ├── selectors.py       ← Reading data (SELECT + optimization)
    ├── services.py        ← Business logic (CREATE / UPDATE / DELETE + side effects)
    ├── serializers.py     ← Input/Output contracts (HTTP ↔ domain)
    ├── views.py           ← Thin HTTP orchestrator
    ├── urls.py            ← URL routes
    ├── tasks.py           ← Celery tasks (transport, not logic)
    ├── filters.py         ← django-filter
    ├── permissions.py     ← DRF permissions
    ├── admin.py           ← Admin configuration
    ├── tests/
    └── migrations/

Mental model: three boundaries

┌─────────────────────────────────────────────────────┐
│  TRANSPORT LAYER                                    │
│  views.py + serializers.py + tasks.py               │
│  "How data arrives and where it goes"               │
├─────────────────────────────────────────────────────┤
│  APPLICATION LAYER                                  │
│  services.py                                        │
│  "WHAT the system does"                             │
├─────────────────────────────────────────────────────┤
│  DATA LAYER                                         │
│  selectors.py + models.py + ORM                     │
│  "Where data comes from and how it's fetched"       │
└─────────────────────────────────────────────────────┘

The rule: each layer knows only about the layer directly beneath it. View → Service → Selector → ORM. No skipping layers.


Connection to the rest of the documentation

Topic File
General Django architecture django_architecture.md
ORM, QuerySet, N+1, transactions Django_ORM.md
Views: FBV, CBV, Generic Django_Views.md
Architecture diagrams (Mermaid) django_mermaid.md
Project structure DJANGO_PROJECT_STRUCTURE.md