Skip to content

Commit

Permalink
Merge pull request #207 from octabytes/feature/improve-to-dict
Browse files Browse the repository at this point in the history
Improve model.to_dict()
  • Loading branch information
AxeemHaider committed May 31, 2023
2 parents d76ed8a + bc920d7 commit 8c9672e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/fireo/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,26 @@ def merge_with_dict(self, model_dict, by_column_name=False):
"""Load data from dict into model."""
self.populate_from_doc_dict(model_dict, merge=True, by_column_name=by_column_name)

def to_dict(self):
def to_dict(
self,
include_id: bool = True,
include_key: bool = True,
include_parent: bool = False,
dump_options=DumpOptions(use_column_name=False)
):
"""Convert model into dict"""
model_dict = self.to_db_dict()
id_field_name, _ = self._meta.id
model_dict[id_field_name] = utils.get_id(self.key)
model_dict['key'] = self.key
model_dict = self.to_db_dict(dump_options)

if include_id:
id_field_name, _ = self._meta.id
model_dict[id_field_name] = utils.get_id(self.key)

if include_key:
model_dict['key'] = self.key

if include_parent:
model_dict['parent'] = self.parent

return model_dict

def to_db_dict(self, dump_options=DumpOptions()):
Expand Down Expand Up @@ -224,7 +238,10 @@ def to_db_dict(self, dump_options=DumpOptions()):
not dump_options.ignore_default_none or
field_changed
):
result[field.db_column_name] = value
if dump_options.use_column_name:
result[field.db_column_name] = value
else:
result[field.name] = value

return result

Expand Down
3 changes: 3 additions & 0 deletions src/fireo/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ class DumpOptions:
"""Ignore fields which are not changed when updating the document.
Used in NestedModelField."""

use_column_name: bool = True
"""Use column name or field name."""


@dataclass(frozen=True)
class LoadOptions:
Expand Down
17 changes: 17 additions & 0 deletions src/tests/v2.1.1/test_to_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from fireo.fields import TextField
from fireo.models import Model


class MyModel(Model):
field = TextField(column_name='my_field')


def test_to_dict_by_field_name_by_default():
instance = MyModel()
instance.field = 'value'

assert instance.to_dict() == {
'field': 'value',
'id': instance.id,
'key': instance.key,
}

0 comments on commit 8c9672e

Please sign in to comment.