AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

コレクションを表すモデルの作成

このガイドでは、 MongoDBコレクションを表す Diango モデルを作成する方法を学習できます。モデルは、データの構造を定義するPythonクラスです。 Dlango MongoDBバックエンドを使用すると、各モデルをMongoDBコレクションにマッピングし、モデル オブジェクトを使用してコレクションのドキュメントを操作できます。

Tip

Diango モデルの詳細については、Diango ドキュメントの Model を参照してください。

このセクションでは、モデルに含めることができる次のフィールドに対する Dlango MongoDBバックエンドのサポートについて説明します。

次の表では、Diango MongoDBバックエンドがサポートする Dlango モデル フィールドについて説明しています。

フィールド型
説明

BinaryField

未加工のバイナリ データを保存します。

BooleanField

ブール値値(True または False)を保存します。

CharField

string 値を保存します。 より長いテキスト値を保存するには、TextField を使用します。

DateField

Python datetime.date インスタンスに日付値を保存します。

DateTimeField

Python datetime.datetime インスタンスに日付と時刻の値を保存します。

DecimalField

10 進数値を保存します。

DurationField

Python timedelta インスタンスに期間を表す値を保存します。

EmailField

CharField値を保存し、EmailValidatorを使用して値がメール アドレスであることを確認します。

FileField

Stores file values.

FilePathField

ファイルシステム上のファイル名を表す CharField 値を保存します。

FloatField

Stores float values.

GenericIPAddressField

IPv4 または IPv6 アドレスを string形式で保存します。

ImageField

FileField 値を保存し、アップロードされたオブジェクトが有効なイメージであることを確認します。

IntegerField および BigIntegerField

サイズが最大 64 ビットまでの整数値を保存します。

JSONField

Stores JSON data. To learn more about this field, see the Store JSON Data section in this guide.

PositiveIntegerField および PositiveBigIntegerField

サイズが 64 ビットまでの正の整数値を保存します。

PositiveSmallIntegerField

サイズが 32 ビットまでの正の整数値を保存します。

SlugField

短いテキスト ラベルを保存します。多くの場合URL値用です。

SmallIntegerField

サイズが最大 32 ビットまでの整数値を保存します。

TextField

大きなテキスト値を保存します。

URLField

URL を表す CharField 値を保存します。

UUIDField

Python の UUIDクラスのインスタンスを保存します。

MongoDB、 BSONと呼ばれるバイナリ形式でドキュメントを整理して保存し、柔軟なデータ処理を可能にしています。

Tip

To learn more about how MongoDB stores BSON data, see BSON Types in the MongoDB Server manual.

次の表では、サポートされているBSONフィールド型と、Diango モデルで使用できるそれに相当する Diango MongoDBバックエンド について説明しています。

BSONフィールド型
Dpango MongoDBバックエンド フィールド型
BSON の説明

Array

ArrayField

Stores array values. To learn more about using this field with Django MongoDB Backend, see the Store Array Data section in this guide.

Object

EmbeddedModelField or EmbeddedModelArrayField

Stores one or multiple embedded documents. To learn more about using these fields with Django MongoDB Backend, see the Store Embedded Model Data and Store Embedded Model Array Data sections.

ObjectId

ObjectIdField

MongoDB がプライマリキーとして使用する一意の 12 バイト識別子を保存します。

Binary

BinaryField

バイナリ データを保存します。

Boolean

BooleanField

true または false 値を保存します。

Date

DatetimeField

Unix エポック、または 1 月 1、1970 からの日付と時刻をミリ秒単位で保存します。

Decimal128

DecimalField

28 ビットの 10 進数値を保存します。

Double

FloatField

浮動小数点値を保存します。

Int32

SmallIntegerField

32 ビットの符号付き整数を保存します。

Int64

IntegerField or BigIntegerField

64 ビットの符号付き整数を保存します。

String

CharField or TextField

UTF-8 でエンコードされた文字列値を保存します。

MongoDBコレクション を表すモデルを作成するには、モデルクラスの定義をアプリケーションの models.pyファイルに追加します。 モデルクラスで、保存するフィールドを指定し、内部 Metaクラスにモデルメタデータを含めます。 また、__str__() メソッドを使用して、モデルの string 表現を定義することもできます。 モデルを定義するには、次の構文を使用します。

class <Model name>(models.Model):
<field name> = <data type>
# Include additional fields here
class Meta:
# Include metadata here
def __str__(self):
# Include logic for displaying your model as a string here

Tip

Metaクラスで指定できるメタデータオプションの詳細については、Diango ドキュメントのモデル メタ オプションを参照してください。

モデルを使用するには、プロジェクトの settings.pyファイルに追加する必要があります。 次のコードに示すように、INSTALLED_APPS の値を編集して、models.pyファイルを保存するモジュールの名前を含めます。

INSTALLED_APPS = [
'<application module>',
# Include other app modules here
]

最後に、プロジェクトのルートディレクトリから次のデータベース移行コマンドを実行して、モデル用のMongoDBコレクションを作成するか、既存のコレクションを使用してモデル データを保存します。

python manage.py makemigrations <application name>
python manage.py migrate

このサンプルmodels.pyファイルは、次の情報を含む Movie モデルクラスを定義します。

  • 映画データを表すフィールドのリスト。

  • Meta class that sets the db_table option to movies. This instructs Django MongoDB Backend to use this model to represent the sample_mflix.movies collection from the Atlas sample datasets.

    また、Metaクラスはmanaged オプションを False に設定し、Dlango MongoDBバックエンドにモデルの新しいコレクションを作成しないように指示します。

  • __str__() メソッドを使用して、モデルの string 表現を titleフィールド値として定義します。

from django.db import models
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

Tip

モデルクラス定義で使用されるフィールドの詳細については、このガイドの「サポートされているフィールド」セクションを参照してください。

このセクションでは、Diango モデルで次のフィールドを使用する方法を示します。

モデルで JSONField を使用してJSONオブジェクトを保存できます。 JSONはデータ交換のための人間が判読可能な形式であり、 JSONオブジェクトは string キーを値にマッピングするデータ コンテナです。 MongoDB はJSONデータをドキュメントに保存するための Objectフィールド型を提供し、このデータをBSON( Binary JSON)形式で内部的に保存します。

注意

埋め込みモデルと多形埋め込みモデルを使用してMongoDB Object を表すこともできます。

The following example adds a JSONField value to the model created in the Define a Model example in this guide. The new field, called imdb, stores JSON data that represents user ratings for each Movie object:

from django.db import models
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
imdb = models.JSONField(null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

Tip

JSONField に保存されているデータをクエリする方法については、クエリの指定ガイドの「JSON値のクエリ」を参照してください。

Dlango MongoDBバックエンドの JSONField のサポートには次の制限があります。

  • フィールドの値を None に設定すると、Diango MongoDBバックエンド はその値をSQL NULL 値として保存します。 あるいは、JSONField の値を Value(None, JSONField()) に設定することもできます。これはJSONスカラー null を表します。 ただし、クエリ時にSQL NULL とJSON null を区別する方法はありません。

  • Q オブジェクトを使用する一部のクエリでは、特に QuerySet.exclude() メソッドを使用する場合、期待どおりの結果が返されないことがあります。

  • Dlango MongoDBバックエンドは、None 値を持つフィールドをクエリすると、フィールドが存在しないドキュメントを誤って返します。

モデルで ArrayField を使用してデータのリストを保存できます。 ArrayField を作成するには、ArrayField()クラスコンストラクタを使用して次の引数を渡します。

  • base_field: 配列に保存される各値の基礎となるデータ型を指定します。 基本フィールドタイプとして EmbeddedModelField または FileField を指定することはできません。

  • size:(任意) 配列の最大サイズを指定します。

  • options : (任意) Djangoフィールドオプションを指定します。使用可能なオプションのリストを表示するには、Diango ドキュメントのフィールド オプションを参照してください。

Tip

次の構文を使用して、配列値の配列を ArrayField に保存できます。

my_array = ArrayField(
ArrayField(
base_field,
# ... Additional arguments
),
)

The following example adds an ArrayField value to the model created in the Define a Model example in this guide. The new field, called genres, stores a list of CharField values that represent movie genres and can store a maximum of 5 values:

from django.db import models
from django_mongodb_backend.fields import ArrayField
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
genres = ArrayField(
models.CharField(max_length=100),
size=5,
null=True,
blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

Tip

ArrayField に保存されているデータをクエリする方法については、クエリの指定ガイドの「配列値のクエリ」を参照してください。

ネストされたドキュメント値を保存するMongoDB Object を表すには、EmbeddedModelField を使用します。 このタイプでは、1 つのモデルが フィールドの 1 つに個別のモデルを保存できます。 EmbeddedModelField を作成するには、埋め込みモデルクラスをEmbeddedModel 抽象モデルのサブクラスとして定義します。 次に、EmbeddedModelField() コンストラクターを使用して基本モデルクラスにフィールドを作成し、次の引数を渡します。

  • embedded_model: 保存するモデルクラスを指定します。

  • options : (任意) Djangoフィールドオプションを指定します。使用可能なオプションのリストを表示するには、Diango ドキュメントのフィールド オプションを参照してください。

重要

makemigrations Diango コマンドは、埋め込みモデルへの変更を検出しません。 埋め込みモデルのクラスに変更を加えた場合、EmbeddedModelField に保存されるモデルは変更を反映しません。

This example adds an EmbeddedModelField value to the model created in the Define a Model example in this guide. The new field, called awards, stores an embedded Award model as its value. The following code defines the Award model and modifies the Movie model to include the EmbeddedModelField:

from django.db import models
from django_mongodb_backend.models import EmbeddedModel
from django_mongodb_backend.fields import EmbeddedModelField
class Award(EmbeddedModel):
wins = models.IntegerField(default=0)
nominations = models.IntegerField(default=0)
text = models.CharField(max_length=100)
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
awards = EmbeddedModelField(Award, null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

Tip

EmbeddedModelField に保存されているデータをクエリする方法については、クエリの指定ガイドの「埋め込みモデル値のクエリ」を参照してください。

EmbeddedModelArrayField を使用して、ドキュメントの配列を 1 対多の関係で保存するMongoDBドキュメントフィールドを表すことができます。配列内の各ドキュメントは、Diango MongoDBバックエンド EmbeddedModelField 値に対応します。EmbeddedModelArrayField を作成するには、EmbeddedModelArrayField()クラスコンストラクタを使用して次の引数を渡します。

  • embedded_model: 各配列項目に保存されているモデルを指定します。

  • max_size:(任意) 配列の最大サイズを指定します。

This example adds an EmbeddedModelArrayField value to the model created in the Define a Model example in this guide. This cast field stores an array of embedded Actor models. The following code defines the Actor model and modifies the Movie model to include the EmbeddedModelArrayField:

from django.db import models
from django_mongodb_backend.models import EmbeddedModel
from django_mongodb_backend.fields import EmbeddedModelArrayField
class Actor(EmbeddedModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
role = models.CharField(max_length=100)
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
cast = EmbeddedModelArrayField(Actor, null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

複数のタイプの埋め込みドキュメントを保存できるMongoDBドキュメントフィールドを表すには、PolymorphicEmbeddedModelField を使用します。各埋め込みドキュメントは、 Diango MongoDBバックエンド モデルクラスによって表されます。

PolymorphicEmbeddedModelField を作成するには、embedded_models 引数を PolymorphicEmbeddedModelField()クラスコンストラクターに渡します。この引数は、フィールドが保存できるモデル クラスのリストを指定します。

This example adds a PolymorphicEmbeddedModelField value to the model created in the Define a Model example in this guide. This awards field can store an embedded model of type Oscars or GoldenGlobes. Each embedded model contains information about all the Oscar or Golden Globe awards a movie has won.

次のコードでは、Oscars と GoldenGlobes の埋め込みモデルを定義し、Movie モデルを変更して PolymorphicEmbeddedModelField を含めます。

from django.db import models
from django_mongodb_backend.models import EmbeddedModel
from django_mongodb_backend.fields import PolymorphicEmbeddedModelField
class Oscars(EmbeddedModel):
wins = models.IntegerField(default=0)
nominations = models.IntegerField(default=0)
best_picture = models.BooleanField(default=False)
class GoldenGlobes(EmbeddedModel):
wins = models.IntegerField(default=0)
nominations = models.IntegerField(default=0)
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
awards = PolymorphicEmbeddedModelField(["Oscars", "GoldenGlobes"], null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

Tip

PolymorphicEmbeddedModelField に保存されているデータをクエリする方法については、クエリの指定ガイドの「多形埋め込みモデル値のクエリ」を参照してください。

複数のタイプの埋め込みドキュメントを保存できるMongoDBドキュメントフィールドを表すには、PolymorphicEmbeddedModelArrayField を使用します。このフィールドはPolymorphicEmbeddedModelField と似ていますが、単一のドキュメントではなく 、埋め込みドキュメントの配列が保存されます。配列内の各埋め込みドキュメントは、 Diango MongoDBバックエンド モデルクラスによって表されます。

PolymorphicEmbeddedModelArrayField を作成するには、次の引数を PolymorphicEmbeddedModelArrayField()クラスコンストラクターに渡します。

  • embedded_models:フィールドが保存できるモデルクラスを指定します

  • max_size: (任意) 配列の最大サイズを指定します

This example adds a PolymorphicEmbeddedModelArrayField value to the model created in the Define a Model example in this guide. This awards field can store a list of embedded models of type Oscar or GoldenGlobe. Each embedded model contains information about one Oscar or Golden Globe award that a movie has won.

次のコードでは、Oscar と GoldenGlobe の埋め込みモデルを定義し、Movie モデルを変更して PolymorphicEmbeddedModelArrayField を含めます。

from django.db import models
from django_mongodb_backend.models import EmbeddedModel
from django_mongodb_backend.fields import PolymorphicEmbeddedModelArrayField
class Oscar(EmbeddedModel):
category = models.CharField(max_length=200)
year = models.IntegerField(default=0)
class GoldenGlobe(EmbeddedModel):
category = models.CharField(max_length=200)
year = models.IntegerField(default=0)
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
awards = PolymorphicEmbeddedModelArrayField(["Oscar", "GoldenGlobe"], null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title

Tip

PolymorphicEmbeddedModelArrayField に保存されているデータをクエリする方法については、 クエリの指定ガイドの「多形埋め込みモデル配列値のクエリ」を参照してください。

モデルを使用してデータベース操作を実行する方法については、「 データの操作 」ガイドを参照してください。

Diango フィールドの詳細については、Diango ドキュメントの モデルフィールドに関する参照 を参照してください。