Skip to content

Commit

Permalink
Merge pull request #2408 from bagerard/refactoring_remove_useless_cod…
Browse files Browse the repository at this point in the history
…e_only_fields

Removed code related to Document.__only_fields
  • Loading branch information
bagerard committed Nov 8, 2020
2 parents cb9f329 + 90c5d83 commit 161493c
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 41 deletions.
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Development
- Bug fix in ListField when updating the first item, it was saving the whole list, instead of
just replacing the first item (as it's usually done) #2392
- Add EnumField: ``mongoengine.fields.EnumField``
- Refactoring - Remove useless code related to Document.__only_fields and Queryset.only_fields

Changes in 0.20.0
=================
Expand Down
17 changes: 3 additions & 14 deletions mongoengine/base/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ def __init__(self, *args, **values):
It may contain additional reserved keywords, e.g. "__auto_convert".
:param __auto_convert: If True, supplied values will be converted
to Python-type values via each field's `to_python` method.
:param __only_fields: A set of fields that have been loaded for
this document. Empty if all fields have been loaded.
:param _created: Indicates whether this is a brand new document
or whether it's already been persisted before. Defaults to true.
"""
Expand All @@ -80,8 +78,6 @@ def __init__(self, *args, **values):

__auto_convert = values.pop("__auto_convert", True)

__only_fields = set(values.pop("__only_fields", values))

_created = values.pop("_created", True)

signals.pre_init.send(self.__class__, document=self, values=values)
Expand All @@ -106,10 +102,8 @@ def __init__(self, *args, **values):
self._dynamic_fields = SON()

# Assign default values to the instance.
# We set default values only for fields loaded from DB. See
# https://github.com/mongoengine/mongoengine/issues/399 for more info.
for key, field in self._fields.items():
if self._db_field_map.get(key, key) in __only_fields:
if self._db_field_map.get(key, key) in values:
continue
value = getattr(self, key, None)
setattr(self, key, value)
Expand Down Expand Up @@ -758,11 +752,8 @@ def _get_collection_name(cls):
return cls._meta.get("collection", None)

@classmethod
def _from_son(cls, son, _auto_dereference=True, only_fields=None, created=False):
def _from_son(cls, son, _auto_dereference=True, created=False):
"""Create an instance of a Document (subclass) from a PyMongo SON."""
if not only_fields:
only_fields = []

if son and not isinstance(son, dict):
raise ValueError(
"The source SON object needs to be of type 'dict' but a '%s' was found"
Expand Down Expand Up @@ -817,9 +808,7 @@ def _from_son(cls, son, _auto_dereference=True, only_fields=None, created=False)
if cls.STRICT:
data = {k: v for k, v in data.items() if k in cls._fields}

obj = cls(
__auto_convert=False, _created=created, __only_fields=only_fields, **data
)
obj = cls(__auto_convert=False, _created=created, **data)
obj._changed_fields = []
if not _auto_dereference:
obj._fields = fields
Expand Down
34 changes: 8 additions & 26 deletions mongoengine/queryset/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ def __init__(self, document, collection):
self._hint = -1 # Using -1 as None is a valid value for hint
self._collation = None
self._batch_size = None
self.only_fields = []
self._max_time_ms = None
self._comment = None

Expand Down Expand Up @@ -190,19 +189,15 @@ def __getitem__(self, key):
if queryset._scalar:
return queryset._get_scalar(
queryset._document._from_son(
queryset._cursor[key],
_auto_dereference=self._auto_dereference,
only_fields=self.only_fields,
queryset._cursor[key], _auto_dereference=self._auto_dereference,
)
)

if queryset._as_pymongo:
return queryset._cursor[key]

return queryset._document._from_son(
queryset._cursor[key],
_auto_dereference=self._auto_dereference,
only_fields=self.only_fields,
queryset._cursor[key], _auto_dereference=self._auto_dereference,
)

raise TypeError("Provide a slice or an integer index")
Expand Down Expand Up @@ -719,12 +714,10 @@ def modify(

if full_response:
if result["value"] is not None:
result["value"] = self._document._from_son(
result["value"], only_fields=self.only_fields
)
result["value"] = self._document._from_son(result["value"])
else:
if result is not None:
result = self._document._from_son(result, only_fields=self.only_fields)
result = self._document._from_son(result)

return result

Expand Down Expand Up @@ -757,18 +750,14 @@ def in_bulk(self, object_ids):
docs = self._collection.find({"_id": {"$in": object_ids}}, **self._cursor_args)
if self._scalar:
for doc in docs:
doc_map[doc["_id"]] = self._get_scalar(
self._document._from_son(doc, only_fields=self.only_fields)
)
doc_map[doc["_id"]] = self._get_scalar(self._document._from_son(doc))
elif self._as_pymongo:
for doc in docs:
doc_map[doc["_id"]] = doc
else:
for doc in docs:
doc_map[doc["_id"]] = self._document._from_son(
doc,
only_fields=self.only_fields,
_auto_dereference=self._auto_dereference,
doc, _auto_dereference=self._auto_dereference,
)

return doc_map
Expand Down Expand Up @@ -841,7 +830,6 @@ def _clone_into(self, new_qs):
"_collation",
"_auto_dereference",
"_search_text",
"only_fields",
"_max_time_ms",
"_comment",
"_batch_size",
Expand Down Expand Up @@ -1045,7 +1033,6 @@ def only(self, *fields):
.. versionchanged:: 0.5 - Added subfield support
"""
fields = {f: QueryFieldList.ONLY for f in fields}
self.only_fields = list(fields.keys())
return self.fields(True, **fields)

def exclude(self, *fields):
Expand Down Expand Up @@ -1310,10 +1297,7 @@ def to_json(self, *args, **kwargs):
def from_json(self, json_data):
"""Converts json data to unsaved objects"""
son_data = json_util.loads(json_data)
return [
self._document._from_son(data, only_fields=self.only_fields)
for data in son_data
]
return [self._document._from_son(data) for data in son_data]

def aggregate(self, pipeline, *suppl_pipeline, **kwargs):
"""Perform a aggregate function based in your queryset params
Expand Down Expand Up @@ -1638,9 +1622,7 @@ def __next__(self):
return raw_doc

doc = self._document._from_son(
raw_doc,
_auto_dereference=self._auto_dereference,
only_fields=self.only_fields,
raw_doc, _auto_dereference=self._auto_dereference,
)

if self._scalar:
Expand Down
2 changes: 1 addition & 1 deletion tests/document/test_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -3434,7 +3434,7 @@ class Test(Document):
assert obj3 != dbref2
assert dbref2 != obj3

def test_default_values(self):
def test_default_values_dont_get_override_upon_save_when_only_is_used(self):
class Person(Document):
created_on = DateTimeField(default=lambda: datetime.utcnow())
name = StringField()
Expand Down

0 comments on commit 161493c

Please sign in to comment.