When your API receives bad data — a discount price higher than the original price, an end date before the start date — the error must be blocked in the Serializer, before it ever touches the database. Django REST Framework gives you two built-in hooks: validate_<field> for checking a single field on its own, and validate() for checking relationships between multiple fields. Use these two hooks correctly, and the view is left with a single line — is_valid(raise_exception=True) — while the client always gets a 400 error attached to the right field.
The Problem
Many projects validate with a pile of if statements right in the view: check the price in create(), check the dates in update(), then copy-paste the same checks into another view. That causes three problems: the validation logic is scattered around, so changing one rule means touching many places; bad data slips down to the database and explodes into a 500 instead of a 400; and the error is not attached to any field, so the frontend cannot highlight the right input.
Another common mistake: writing validate_<field> but forgetting return value. DRF takes the return value — that is, None — as the field’s value, so perfectly valid data silently becomes None with no error reported.
# Cách làm dễ sai: validate bằng if trong view, lặp lại ở mọi viewdef create(self, request): price = request.data.get("price") discount = request.data.get("discount_price") if discount and discount > price: return Response( {"error": "Giá khuyến mãi không được lớn hơn giá gốc."}, status=status.HTTP_400_BAD_REQUEST, ) # ... rồi lại lặp lại đoạn này ở update()
The Solution
Move every rule into the Serializer — for example, a course with an original price, a discount price, and a date range:
from rest_framework import serializersfrom .models import Courseclass CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ["id", "name", "price", "discount_price", "start_date", "end_date"] read_only_fields = ["id"] extra_kwargs = {"price": {"min_value": 0}} def validate_name(self, value): value = value.strip() if len(value) < 3: raise serializers.ValidationError( "Tên khóa học phải có ít nhất 3 ký tự.") return value def validate_discount_price(self, value): if value is not None and value < 0: raise serializers.ValidationError( "Giá khuyến mãi không được âm.") return value def validate(self, data): price = data.get("price") discount = data.get("discount_price") if (price is not None and discount is not None and discount > price): raise serializers.ValidationError( {"discount_price": "Giá khuyến mãi không được lớn hơn giá gốc."}) start = data.get("start_date") end = data.get("end_date") if start is not None and end is not None and end <= start: raise serializers.ValidationError( {"end_date": "Ngày kết thúc phải sau ngày bắt đầu."}) return data
Three things to remember. First, validate_<field> receives a value that has already passed type checks, and it must return value — forget the return and the field becomes None. Second, validate() runs after all per-field checks, and any field that failed validation is absent from data — so use data.get() instead of data[...]. Third, if you raise ValidationError with a dict, the error is attached to the named field; if you raise a bare string, the error lands in non_field_errors.
The view is then left with a single line, and DRF returns a 400 with a JSON error automatically:
serializer = CourseSerializer(data=request.data)serializer.is_valid(raise_exception=True)serializer.save()
Send a discount_price larger than price, and the client immediately gets {"discount_price": ["Giá khuyến mãi không được lớn hơn giá gốc."]} with a 400 status — no extra error-handling code needed in the view.
Apply It to Your Project
Move the if data checks out of your views and into the Serializer: a rule for a single field goes in validate_<field>, a rule spanning multiple fields goes in validate(). That way all validation rules live in one place — add a field or change a rule and you only edit one spot, and every endpoint using the same Serializer picks up the new rule immediately.
Related Posts
- Django REST Framework: Write Serializers the Right Way — ModelSerializer, depth, and SerializerMethodField
- FastAPI: Validate Input Data Properly with Pydantic Field and Custom Validators
- Django REST Framework: Permissions and API Spam Protection with Permission + Throttling in 5 Minutes
Frequently Asked Questions
Does validate_<field> run before validate()?
validate_<field> runs first, after the field has passed type checks and constraints such as min_value. validate() runs last, with data containing only the fields that passed validation. That is why inside validate() you should use data.get("price") instead of data["price"] — to avoid a KeyError when price already failed validation.
What happens if I forget return value in validate_<field>?
DRF uses the function’s return value as the field’s new value, so forgetting return value silently overwrites the field with None. Treat return value as a mandatory final line in every validate_<field>.
Should I validate in the Serializer or in the model?
Validate API input in the Serializer — it is the layer that touches client data directly and returns a proper 400 error. The model’s clean() suits business rules shared across many entry points — creating records from the admin, the shell, or an import script — where the data does not go through a Serializer.
Should ValidationError raise a string or a dict?
Raise a dict when the error belongs to a specific field, for example {"discount_price": "..."} — the client knows exactly which input is wrong. Raise a string only when the error concerns the data as a whole; in that case it ends up in non_field_errors.
💬 Have you tried this in your own project? If you hit an error or know a shorter way, leave a comment below — I read them all and will add the best ideas to the post.
References
- Django REST Framework Documentation — Serializers: Validation: https://www.django-rest-framework.org/api-guide/serializers/#validation
- Django REST Framework Documentation — Fields: https://www.django-rest-framework.org/api-guide/fields/
