Skip to content

DOCSP-46325: Models #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ api = "https://django-mongodb.readthedocs.io/en/latest/"
mdb-server = "MongoDB Server"
django-version = "5.0"
django-docs = "https://docs.djangoproject.com/en/{+django-version+}"
framework = "Django"
28 changes: 28 additions & 0 deletions source/includes/model-data/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# start-models
from django.db import models
from django_mongodb_backend.fields import EmbeddedModelField, ArrayField

class Award(models.Model):
wins = models.IntegerField(default=0)
nominations = models.IntegerField(default=0)
text = models.CharField(max_length=100)

class Meta:
managed = False

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)
genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)
imdb = models.JSONField(null=True)

class Meta:
db_table = "movies"
managed = False

def __str__(self):
return self.title
# end-models
25 changes: 25 additions & 0 deletions source/model-data.txt
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming there are more pages to come that will be nested here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep, the indexes page will also go here

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.. _django-model-data:

===============
Model Your Data
===============

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:description: Learn how to use Django MongoDB Backend to model MongoDB data.
:keywords: field, query, collection, object

.. toctree::
:titlesonly:
:maxdepth: 1

Create Models </model-data/models>
258 changes: 258 additions & 0 deletions source/model-data/models.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
.. _django-models:

=============
Create Models
=============

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: class, field, code example

Overview
--------

In this guide, you can learn how to create {+framework+} **models** that
represent MongoDB collections. Models are Python classes that define
the structure of your data. When using {+django-odm+}, you can
map each model to a MongoDB collection and interact with the collection's
documents by using model objects.

.. tip::

To learn more about {+framework+} models, see `Models
<{+django-docs+}/topics/db/models/>`__ in the {+framework+}
documentation.

.. _django-models-define:

Define a Model
--------------

To create an model that represents a MongoDB collection, add your model
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To create a model

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for catching!

class definitions to your application's ``models.py`` file. In your model
class, specify the fields you want to store and include any model metadata
in an inner ``Meta`` class. You can also use the ``__str__()`` method to
define a string representation of your model. Use the following syntax to
define a model:

.. code-block:: python

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

To use your models, you must add them to your project's
``settings.py`` file. Edit the ``INSTALLED_APPS`` value to include
the name of the module that stores your ``models.py`` file, as shown
in the following code:

.. code-block:: python

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

Finally, run the following database migration commands from your
project's root directory to create MongoDB collections for your
models or use existing collections to store model data:

.. code-block:: bash

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

Example
```````

This sample ``models.py`` file defines ``Movie`` and ``Award``
models. The ``Movie`` class includes the following information:

- List of fields that represent movie data, including
an ``awards`` field that stores an embedded ``Award`` model.

- ``Meta`` class that sets the ``db_table`` option
to ``movies``. This instructs {+django-odm+} to use this model
to represent the ``sample_mflix.movies`` collection from the
:atlas:`Atlas sample datasets </sample-data>`.

The ``Meta`` class also sets the ``managed`` option to ``False``,
instructing {+django-odm+} not to create a new collection
for the model.

- ``__str__()`` method that defines the model's string
representation as its ``title`` field value.

The ``Award`` model stores data for the ``Movie`` model's
``awards`` field. Its class includes the following information:

- List of fields that represent movie award data.

- ``Meta`` class that sets the ``managed`` option to ``False``.
This instructs {+django-odm+} not to create a new collection
for the model.

.. literalinclude:: /includes/model-data/models.py
:start-after: start-models
:end-before: end-models
:language: python
:copyable:

.. tip::

To learn more about the field types used in the model
class definitions, see the following :ref:`django-models-fields`
section of this guide.

.. _django-models-fields:

Supported Field Types
---------------------

This section describes {+django-odm+}'s support for
the following field types:

- :ref:`django-models-django-fields`
- :ref:`django-models-mongodb-fields`

.. _django-models-django-fields:

{+framework+} Fields
~~~~~~~~~~~~~~~~~~~~

The following table describes the {+framework+} model fields
that {+django-odm+} supports:

.. list-table::
:header-rows: 1
:widths: 20 80

* - Field Type
- Description

* - ``AutoField``
- | Stores ``IntegerField`` values that automatically increment according to
available ID values. If you don't explicitly specify this field,
MongoDB automatically assigns an ``ObjectId`` primary key value.

* - ``BigAutoField``
- | Stores ``AutoField`` values up to 64 bits in size.

* - ``BigIntegerField``
- | Stores ``IntegerField`` values up to 64 bits in size.

* - ``BinaryField``
- | Stores raw binary data.

* - ``BooleanField``
- | Stores boolean (``True`` or ``False``) values.

* - ``CharField``
- | Stores string values. To store longer text values, use
``TextField``.

* - ``DateField``
- | Stores date values in Python ``datetime.date`` instances.

* - ``DateTimeField``
- | Stores date and time values in Python ``datetime.datetime``
instances.

* - ``DecimalField``
- | Stores decimal values.

* - ``DurationField``
- | Stores values representing periods of time in
Python ``timedelta`` instances.

* - ``EmailField``
- | Stores ``CharField`` values and uses an `EmailValidator
<{+django-docs+}/ref/validators/#django.core.validators.EmailValidator>`__
to verify that the value is an email address.

* - ``FileField``
- | Stores file values.

* - ``FilePathField``
- | Stores ``CharField`` values that represent filenames on your filesystem.

* - ``FloatField``
- | Stores float values.

* - ``GenericIPAddressField``
- | Stores an Pv4 or IPv6 address in string format.

* - ``IntegerField``
- | Stores integer values.

* - ``JSONField``
- | Stores JSON data. To learn more about this field, see the
:ref:`django-models-json` section in this guide.

* - ``PositiveBigIntegerField``
- | Stores positive integer values up to 64 bits in size.

* - ``PositiveIntegerField``
- | Stores positive integer values up to 32 bits in size.

* - ``PositiveSmallIntegerField``
- | Stores positive integer values up to 16 bits in size.

* - ``SlugField``
- | Stores a short text label, often for URL values.

* - ``SmallIntegerField``
- | Stores integer values up to 16 bits in size.

* - ``TextField``
- | Stores large text values.

* - ``URLField``
- | Stores a ``CharField`` value representing a URL.

* - ``UUIDField``
- | Stores instances of Python's ``UUID`` class.

.. _django-models-json:

Use a JSONField
```````````````

.. _django-models-mongodb-fields:

MongoDB Fields
~~~~~~~~~~~~~~

The following table describes field types specific to
{+django-odm+} that you can use in your models:

Use an ArrayField
`````````````````

Use an EmbeddedModelField
`````````````````````````

Additional Information
----------------------

To learn how to use your models to run database operations,
see the :ref:`interact-data` guides.

To learn more about {+framework+} field types, see `Model index reference
<{+django-docs+}/ref/models/fields/>`__ in the {+framework+}
documentation.
Loading