---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/db/models/fields/files.py:FileField`) is just a `"VARCHAR"` storing a relative path string like `"editions/2026-11-25.txt"`. Yet in Python, accessing that attribute gives you an object with `FieldFile.url`, `FieldFile.size`, `FieldFile.open`, `FileProxyMixin.read` (`django/core/files/utils.py: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` (`django/core/files/storage/handler.py:StorageHandler`), backing `django.core.files.storage.storages` and the `"settings.STORAGES"` dictionary (containing `"default"` for user media and `"staticfiles"` for collected static assets). Indexing `storages["default"]` lazily imports and instantiates the configured `Storage` (`django/core/files/storage/base.py: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._save`** (`django/core/files/storage/filesystem.py:FileSystemStorage._save`) writes bytes safely under concurrent requests:

1. **Path-traversal protection:** `FileSystemStorage.path` runs `safe_join(self.location, name)`, refusing any `".."` path that would escape `"MEDIA_ROOT"` (`SuspiciousFileOperation`).
2. **Collision-safe atomic creation:** Unless `"allow_overwrite=True"`, `FileSystemStorage._save` opens the target path with low-level `os.open` flags `os.O_WRONLY | os.O_CREAT | os.O_EXCL`. Because `O_CREAT | O_EXCL` is atomic in the OS kernel, if two concurrent uploads both picked `"editions/2026-11-25.txt"`, the second process receives `FileExistsError`, calls `get_available_name` to append a random 7-character suffix, and retries cleanly instead of silently clobbering the first upload!
3. **Exclusive lock & chunked streaming:** While streaming `"content.chunks()"` to disk, Django acquires `locks.LOCK_EX` so another reader cannot observe a half-written file.

## `FileDescriptor`, lazy `FieldFile`, and why `Model.delete` keeps the file

Now open **`FileDescriptor.__get__`** (`django/db/models/fields/files.py:FileDescriptor.__get__`, subclassing `DeferredAttribute`) and **`FieldFile`** (`django/db/models/fields/files.py:FieldFile`):

- When the ORM hydrates a model row from SQL, the instance's `"__dict__"` holds only the raw `str` path from the database column (`"editions/2026-11-25.txt"`).
- The first time Python accesses the attribute, `FileDescriptor.__get__` wraps that string inside a `FieldFile(instance, field, name)` and caches it in `"instance.__dict__"` — passing `file=None` to `File.__init__`! Notice **`FieldFile._file` is `None` and `FieldFile.closed` is `True`**: zero file descriptors are opened, zero disk `stat()` calls run, and zero S3 requests happen!
- Only when your code touches `FieldFile.file` (which invokes `FieldFile._get_file`, `django/db/models/fields/files.py:FieldFile._get_file`), calls `FieldFile.open()`, or calls `read()` does Django finally execute `"self.storage.open(self.name, 'rb')"`! (Accessing `FieldFile.url` calls `"self.storage.url(self.name)"` — pure string concatenation on `FileSystemStorage`, still zero file I/O!)

Finally, understand one deliberate Django design decision that surprises almost everyone once: **calling `"instance.delete()"` (or `QuerySet.delete()`) NEVER deletes the underlying file from storage!** Django removed automatic file deletion on row delete intentionally for two rock-solid systems reasons:

1. **Transactions cannot roll back external storage:** If you delete a model row inside `django.db.transaction.atomic` and a later step raises an exception, PostgreSQL rolls back the row cleanly — but if Django had already called `"storage.delete()"`, the file on disk or S3 would be permanently gone, leaving a dangling broken row!
2. **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.delete(save=False)` inside `django.db.transaction.on_commit` — or sweep unreferenced blobs asynchronously via a scheduled task!

Watch `storages`, `FileSystemStorage` collision renaming, and `FieldFile` staying strictly unopened until `FileProxyMixin.read` executes live:

```text recording=ch12-services
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.local.Local` manages per-thread and per-coroutine active languages and timezones, and what happens when a naive `datetime.datetime` hits a `DateTimeField` (`django/db/models/fields/__init__.py:DateTimeField`) — in [Thread-local languages and aware datetimes](i18n-and-timezones.md).
