12.5 Caching, signals, tasks, and files
Storage, FieldFile, and lazy file opening
Why does accessing a file field attribute on a model instance never open a file on disk until code reads bytes, and how does StorageHandler decouple models from local filesystems vs. object stores?
In the database, a Django FileField is just a "VARCHAR" storing a relative path string like "editions/. Yet in Python, accessing that attribute gives you an object with FieldFile.url, FieldFile.size, FieldFile.open, FileProxyMixin, and FieldFile.save — without ever calling open() on disk or making an HTTP "GET" to S3 while you iterate a QuerySet of 500 models! Two clean abstractions make that work: StorageHandler and FileDescriptor + FieldFile.
StorageHandler and atomic FileSystemStorage._save
Open StorageHandler, backing django and the "settings dictionary (containing "default" for user media and "staticfiles" for collected static assets). Indexing storages["default"] lazily imports and instantiates the configured Storage subclass once and caches it in "self._storages" — letting you switch a project from local disk (FileSystemStorage) to S3 or GCS by changing one dictionary entry in "STORAGES" without modifying a single model or migration!
Look closely at how FileSystemStorage writes bytes safely under concurrent requests:
- Path-traversal protection:
FileSystemStorageruns.path safe_join(self, refusing any.location, name) ".."path that would escape"MEDIA_ROOT"(SuspiciousFileOperation). - Collision-safe atomic creation: Unless
"allow_overwrite=True",FileSystemStorageopens the target path with low-level._save os.openflagsos. Because.O_WRONLY | os .O_CREAT | os .O_EXCL O_CREAT | O_EXCLis atomic in the OS kernel, if two concurrent uploads both picked"editions/, the second process receives2026-11-25 .txt" FileExistsError, callsget_available_nameto append a random 7-character suffix, and retries cleanly instead of silently clobbering the first upload! - Exclusive lock & chunked streaming: While streaming
"contentto disk, Django acquires.chunks()" locks.LOCK_EXso another reader cannot observe a half-written file.
FileDescriptor, lazy FieldFile, and why Model.delete keeps the file
Now open FileDescriptor (FileDescriptor, subclassing DeferredAttribute) and FieldFile:
- When the ORM hydrates a model row from SQL, the instance’s
"__dict__"holds only the rawstrpath from the database column ("editions/).2026-11-25 .txt" - The first time Python accesses the attribute,
FileDescriptorwraps that string inside a.__get__ FieldFile(instance, field, name)and caches it in"instance— passing.__dict__" file=NonetoFile.__init__! NoticeFieldFile._fileisNoneandFieldFile.closedisTrue: zero file descriptors are opened, zero diskstat()calls run, and zero S3 requests happen! - Only when your code touches
FieldFile.file(which invokesFieldFile,._get_file FieldFile), calls._get_file FieldFile.open(), or callsread()does Django finally execute"self! (Accessing.storage .open(self .name, 'rb')" FieldFile.urlcalls"self— pure string concatenation on.storage .url(self .name)" FileSystemStorage, still zero file I/O!)
Finally, understand one deliberate Django design decision that surprises almost everyone once: calling "instance (or QuerySet) NEVER deletes the underlying file from storage! Django removed automatic file deletion on row delete intentionally for two rock-solid systems reasons:
- Transactions cannot roll back external storage: If you delete a model row inside
djangoand a later step raises an exception, PostgreSQL rolls back the row cleanly — but if Django had already called.db .transaction .atomic "storage, the file on disk or S3 would be permanently gone, leaving a dangling broken row!.delete()" - Shared paths across rows and backups: Two rows (e.g., cloned drafts, fixtures, or database snapshots) can reference the same stored filename; deleting one row must never corrupt another row’s media.
If you want orphaned media cleaned up, trigger FieldFile inside django — or sweep unreferenced blobs asynchronously via a scheduled task!
Watch storages, FileSystemStorage collision renaming, and FieldFile staying strictly unopened until FileProxyMixin executes live:
5. StorageHandler, FileSystemStorage, and FieldFile lazy opening
storages_aliases=['default', 'staticfiles'] saved_name='editions/2026-11-25.txt' collision_renamed=True
fieldfile_lazy: closed_before=True opened_before_read=False opened_on_read=True bytes=16 url='/media/editions/2026-11-25.txt'
Now we close Part III with Django’s fifth horizontal service — how asgiref manages per-thread and per-coroutine active languages and timezones, and what happens when a naive datetime hits a DateTimeField — in Thread-local languages and aware datetimes.