Skip to content

Commit 51afeca

Browse files
authored
Merge pull request MongoEngine#2658 from 1Mark/document_db_field_with_example
Add an example on how to use the db_field to the docs in 2.3.3.1
2 parents 5a325a6 + e74abf7 commit 51afeca

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

docs/guide/defining-documents.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,33 @@ arguments can be set on all fields:
113113
:attr:`db_field` (Default: None)
114114
The MongoDB field name.
115115

116+
If set, operations in MongoDB will be performed with this value instead of the class attribute.
117+
118+
This allows you to use a different attribute than the name of the field used in MongoDB. ::
119+
120+
from mongoengine import *
121+
122+
class Page(Document):
123+
page_number = IntField(db_field="pageNumber")
124+
125+
# Create a Page and save it
126+
Page(page_number=1).save()
127+
128+
# How 'pageNumber' is stored in MongoDB
129+
Page.objects.as_pymongo() # [{'_id': ObjectId('629dfc45ee4cc407b1586b1f'), 'pageNumber': 1}]
130+
131+
# Retrieve the object
132+
page: Page = Page.objects.first()
133+
134+
print(page.page_number) # prints 1
135+
136+
print(page.pageNumber) # raises AttributeError
137+
138+
.. note:: If set, use the name of the attribute when defining indexes in the :attr:`meta`
139+
dictionary rather than the :attr:`db_field` otherwise, :class:`~mongoengine.LookUpError`
140+
will be raised.
141+
142+
116143
:attr:`required` (Default: False)
117144
If set to True and the field is not set on the document instance, a
118145
:class:`~mongoengine.ValidationError` will be raised when the document is

0 commit comments

Comments
 (0)