Django
model.save()
full_clean()
data validation
web development

Why doesn't django's model.save call full_clean?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Django, a powerful and popular web framework for Python, provides a robust Object-Relational Mapping (ORM) layer that allows developers to define their data models as Python classes. One of the central points of interaction with Django's ORM is the `Model.save()` method, which is used to create or update records in the database. However, some developers are puzzled to learn that `Model.save()` does not automatically call `full_clean()`, a method that runs validators and ensures data integrity. This article delves into why this decision was made, its implications, and how developers can incorporate cleaning logic into their workflows if necessary.

Why `Model.save()` Does Not Call `full_clean()`

Separation of Concerns

The primary reason `save()` does not call `full_clean()` stems from the principle of separation of concerns. In software engineering, this principle emphasizes the separation of a software program into distinct sections, with minimal overlap in functionality. Here’s how it relates to Django's design:

  • Model Validation: `full_clean()` is responsible for validating the data against field definitions and any custom validators. Its main purpose is to ensure the data meets all the specified constraints.
  • Persistence Logic: `Model.save()` is concerned with writing data to the database. By not calling `full_clean()`, Django allows developers more flexibility to decide when and where validation should occur within the application’s workflow.

This separation provides developers the freedom to perform validation in forms, views, or serializers, rather than relying solely on model methods. The distinction ensures that data persistence and data integrity are handled independently.

Performance Considerations

Validation can be computationally expensive, especially when dealing with complex field validators, database lookups, or multiple records. If `save()` were to call `full_clean()` every time, it might lead to performance bottlenecks, particularly in bulk operations or when saving numerous objects in a loop.

To illustrate, consider the following example:

  • User Input Validation: It's important to validate data received from users, which is often achieved through Django forms, serializers, or explicitly calling `full_clean()` before saving an object.
  • Importing Data: When importing data from external sources, invoking `full_clean()` ensures that data conforms to the model's structure and validation rules before being saved.

Course illustration
Course illustration

All Rights Reserved.