File オブジェクト¶django.core.files モジュールとそのサブモジュールでは、Django の基本的なファイルハンドリングに関するビルトインクラスが定義されています。
File クラス¶The File class is a thin wrapper around a Python
file object with some Django-specific additions.
Internally, Django uses this class when it needs to represent a file.
File オブジェクトには次の属性とメソッドを持ちます。
MEDIA_ROOT からの相対パスを含むファイル名です。
The underlying file object that this class wraps.
この属性をサブクラスで扱う場合には注意が必要です。
Some subclasses of File, including
ContentFile and
FieldFile, may replace this
attribute with an object other than a Python file
object. In these cases, this attribute may itself be a
File subclass (and not necessarily the same subclass).
Whenever possible, use the attributes and methods of the subclass
itself rather than the those of the subclass's file attribute.
ファイルの読み込み/書き込みのモードです。
Open or reopen the file (which also does File.seek(0)).
The mode argument allows the same values
as Python's built-in open(). *args and **kwargs
are passed after mode to Python's built-in open().
ファイルを再オープンする際、 mode はファイルが元々開かれていたモードを上書きします。 None はオリジナルのモードで再オープンすることを意味します。
コンテキストマネージャとして使用できます。たとえば、 with file.open() as f: のようにです。
ファイルをイテレートし、指定されたサイズの「チャンク」を生成します。 chunk_size のデフォルトは 64 KB です。
これは非常に大きなファイルに特に便利であり、ディスクからストリーミングしてメモリ全体にファイルを保存することを避けることができます。
chunk_size (一括サイズ) で指定されたファイルの全内容にアクセスするために複数のチャンクが必要な場合は True を返します。
リストされたメソッドに加えて、File は、その file オブジェクトの以下の属性とメソッドを公開しています: encoding, fileno, flush, isatty, newlines, read, readinto, readline, readlines, seek, tell, truncate, write, writelines, readable(), writable(), および seekable() 。
ContentFile クラス¶ImageFile クラス¶オブジェクト(以下の Car.photo のように)に関連付けられた File には、いくつかの追加メソッドも用意されています。
提供されたファイル名と内容で新しいファイルを保存します。これは既存のファイルを置き換えるものではありませんが、新しいファイルを作成し、オブジェクトがそれを指すように更新します。 save が True の場合、ファイルが保存されたらモデルの save() メソッドが一度呼び出されます。つまり、次の二行です:
>>> car.photo.save("myphoto.jpg", content, save=False)
>>> car.save()
これは以下と同等です:
>>> car.photo.save("myphoto.jpg", content, save=True)
content 引数は、 File または File のサブクラス(例えば、 ContentFile など)のインスタンスでなければなりません。
モデルインスタンスからファイルを削除し、基になるファイルも削除します。 save が True の場合、ファイルが削除された後にモデルの save() メソッドが一度呼び出されます。
12月 04, 2025