Skip to content

Commit 84a8757

Browse files
committed
DOCSP-46325: Models
1 parent f8c7bd5 commit 84a8757

File tree

4 files changed

+312
-0
lines changed

4 files changed

+312
-0
lines changed

snooty.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ api = "https://django-mongodb.readthedocs.io/en/latest/"
1313
mdb-server = "MongoDB Server"
1414
django-version = "5.0"
1515
django-docs = "https://docs.djangoproject.com/en/{+django-version+}"
16+
framework = "Django"
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# start-models
2+
from django.db import models
3+
from django_mongodb_backend.fields import EmbeddedModelField, ArrayField
4+
5+
class Award(models.Model):
6+
wins = models.IntegerField(default=0)
7+
nominations = models.IntegerField(default=0)
8+
text = models.CharField(max_length=100)
9+
10+
class Meta:
11+
managed = False
12+
13+
class Movie(models.Model):
14+
title = models.CharField(max_length=200)
15+
plot = models.TextField(blank=True)
16+
runtime = models.IntegerField(default=0)
17+
released = models.DateTimeField("release date", null=True, blank=True)
18+
awards = EmbeddedModelField(Award)
19+
genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)
20+
imdb = models.JSONField(null=True)
21+
22+
class Meta:
23+
db_table = "movies"
24+
managed = False
25+
26+
def __str__(self):
27+
return self.title
28+
# end-models

source/model-data.txt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
.. _django-model-data:
2+
3+
===============
4+
Model Your Data
5+
===============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:description: Learn how to use Django MongoDB Backend to model MongoDB data.
19+
:keywords: field, query, collection, object
20+
21+
.. toctree::
22+
:titlesonly:
23+
:maxdepth: 1
24+
25+
Create Models </model-data/models>

source/model-data/models.txt

Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
.. _django-models:
2+
3+
=============
4+
Create Models
5+
=============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: class, field, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to create {+framework+} **models** that
24+
represent MongoDB collections. Models are Python classes that define
25+
the structure of your data. When using {+django-odm+}, you can
26+
map each model to a MongoDB collection and interact with the collection's
27+
documents by using model objects.
28+
29+
.. tip::
30+
31+
To learn more about {+framework+} models, see `Models
32+
<{+django-docs+}/topics/db/models/>`__ in the {+framework+}
33+
documentation.
34+
35+
.. _django-models-define:
36+
37+
Define a Model
38+
--------------
39+
40+
To create an model that represents a MongoDB collection, add your model
41+
class definitions to your application's ``models.py`` file. In your model
42+
class, specify the fields you want to store and include any model metadata
43+
in an inner ``Meta`` class. You can also use the ``__str__()`` method to
44+
define a string representation of your model. Use the following syntax to
45+
define a model:
46+
47+
.. code-block:: python
48+
49+
class <Model name>(models.Model):
50+
<field name> = <data type>
51+
# Include additional fields here
52+
53+
class Meta:
54+
# Include metadata here
55+
56+
def __str__(self):
57+
# Include logic for displaying your model as a string here
58+
59+
To use your models, you must add them to your project's
60+
``settings.py`` file. Edit the ``INSTALLED_APPS`` value to include
61+
the name of the module that stores your ``models.py`` file, as shown
62+
in the following code:
63+
64+
.. code-block:: python
65+
66+
INSTALLED_APPS = [
67+
'<application module>',
68+
# Include other app modules here
69+
]
70+
71+
Finally, run the following database migration commands from your
72+
project's root directory to create MongoDB collections for your
73+
models or use existing collections to store model data:
74+
75+
.. code-block:: bash
76+
77+
python manage.py makemigrations <application name>
78+
python manage.py migrate
79+
80+
Example
81+
```````
82+
83+
This sample ``models.py`` file defines ``Movie`` and ``Award``
84+
models. The ``Movie`` class includes the following information:
85+
86+
- List of fields that represent movie data, including
87+
an ``awards`` field that stores an embedded ``Award`` model.
88+
89+
- ``Meta`` class that sets the ``db_table`` option
90+
to ``movies``. This instructs {+django-odm+} to use this model
91+
to represent the ``sample_mflix.movies`` collection from the
92+
:atlas:`Atlas sample datasets </sample-data>`.
93+
94+
The ``Meta`` class also sets the ``managed`` option to ``False``,
95+
instructing {+django-odm+} not to create a new collection
96+
for the model.
97+
98+
- ``__str__()`` method that defines the model's string
99+
representation as its ``title`` field value.
100+
101+
The ``Award`` model stores data for the ``Movie`` model's
102+
``awards`` field. Its class includes the following information:
103+
104+
- List of fields that represent movie award data.
105+
106+
- ``Meta`` class that sets the ``managed`` option to ``False``.
107+
This instructs {+django-odm+} not to create a new collection
108+
for the model.
109+
110+
.. literalinclude:: /includes/model-data/models.py
111+
:start-after: start-models
112+
:end-before: end-models
113+
:language: python
114+
:copyable:
115+
116+
.. tip::
117+
118+
To learn more about the field types used in the model
119+
class definitions, see the following :ref:`django-models-fields`
120+
section of this guide.
121+
122+
.. _django-models-fields:
123+
124+
Supported Field Types
125+
---------------------
126+
127+
This section describes {+django-odm+}'s support for
128+
the following field types:
129+
130+
- :ref:`django-models-django-fields`
131+
- :ref:`django-models-mongodb-fields`
132+
133+
.. _django-models-django-fields:
134+
135+
{+framework+} Fields
136+
~~~~~~~~~~~~~~~~~~~~
137+
138+
The following table describes the {+framework+} model fields
139+
that {+django-odm+} supports:
140+
141+
.. list-table::
142+
:header-rows: 1
143+
:widths: 20 80
144+
145+
* - Field Type
146+
- Description
147+
148+
* - ``AutoField``
149+
- | Stores ``IntegerField`` values that automatically increment according to
150+
available ID values. If you don't explicitly specify this field,
151+
MongoDB automatically assigns an ``ObjectId`` primary key value.
152+
153+
* - ``BigAutoField``
154+
- | Stores ``AutoField`` values up to 64 bits in size.
155+
156+
* - ``BigIntegerField``
157+
- | Stores ``IntegerField`` values up to 64 bits in size.
158+
159+
* - ``BinaryField``
160+
- | Stores raw binary data.
161+
162+
* - ``BooleanField``
163+
- | Stores boolean (``True`` or ``False``) values.
164+
165+
* - ``CharField``
166+
- | Stores string values. To store longer text values, use
167+
``TextField``.
168+
169+
* - ``DateField``
170+
- | Stores date values in Python ``datetime.date`` instances.
171+
172+
* - ``DateTimeField``
173+
- | Stores date and time values in Python ``datetime.datetime``
174+
instances.
175+
176+
* - ``DecimalField``
177+
- | Stores decimal values.
178+
179+
* - ``DurationField``
180+
- | Stores values representing periods of time in
181+
Python ``timedelta`` instances.
182+
183+
* - ``EmailField``
184+
- | Stores ``CharField`` values and uses an `EmailValidator
185+
<{+django-docs+}/ref/validators/#django.core.validators.EmailValidator>`__
186+
to verify that the value is an email address.
187+
188+
* - ``FileField``
189+
- | Stores file values.
190+
191+
* - ``FilePathField``
192+
- | Stores ``CharField`` values that represent filenames on your filesystem.
193+
194+
* - ``FloatField``
195+
- | Stores float values.
196+
197+
* - ``GenericIPAddressField``
198+
- | Stores an Pv4 or IPv6 address in string format.
199+
200+
* - ``IntegerField``
201+
- | Stores integer values.
202+
203+
* - ``JSONField``
204+
- | Stores JSON data. To learn more about this field, see the
205+
:ref:`django-models-json` section in this guide.
206+
207+
* - ``PositiveBigIntegerField``
208+
- | Stores positive integer values up to 64 bits in size.
209+
210+
* - ``PositiveIntegerField``
211+
- | Stores positive integer values up to 32 bits in size.
212+
213+
* - ``PositiveSmallIntegerField``
214+
- | Stores positive integer values up to 16 bits in size.
215+
216+
* - ``SlugField``
217+
- | Stores a short text label, often for URL values.
218+
219+
* - ``SmallIntegerField``
220+
- | Stores integer values up to 16 bits in size.
221+
222+
* - ``TextField``
223+
- | Stores large text values.
224+
225+
* - ``URLField``
226+
- | Stores a ``CharField`` value representing a URL.
227+
228+
* - ``UUIDField``
229+
- | Stores instances of Python's ``UUID`` class.
230+
231+
.. _django-models-json:
232+
233+
Use a JSONField
234+
```````````````
235+
236+
.. _django-models-mongodb-fields:
237+
238+
MongoDB Fields
239+
~~~~~~~~~~~~~~
240+
241+
The following table describes field types specific to
242+
{+django-odm+} that you can use in your models:
243+
244+
Use an ArrayField
245+
`````````````````
246+
247+
Use an EmbeddedModelField
248+
`````````````````````````
249+
250+
Additional Information
251+
----------------------
252+
253+
To learn how to use your models to run database operations,
254+
see the :ref:`interact-data` guides.
255+
256+
To learn more about {+framework+} field types, see `Model index reference
257+
<{+django-docs+}/ref/models/fields/>`__ in the {+framework+}
258+
documentation.

0 commit comments

Comments
 (0)