Skip to content

Commit

Permalink
feat: serialize models into dict
Browse files Browse the repository at this point in the history
  • Loading branch information
vinyguedess committed Jun 21, 2021
1 parent 9e99eca commit 65defb6
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
14 changes: 14 additions & 0 deletions alcherializer/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ def __init__(self, instance=None, data=None, **kwargs):
self.partial = kwargs.get("partial", False)
self.validated_data = {}

@property
def data(self) -> Dict[str, Any]:
instances = self.instance if self.many else [self.instance]

results = []
for instance in instances:
obj_dict = {}
for key in self.fields.keys():
obj_dict[key] = getattr(instance, key)

results.append(obj_dict)

return results if self.many else results[0]

def clear(self) -> None:
self.errors = {}
self.validated_data = {}
Expand Down
38 changes: 38 additions & 0 deletions tests/unit/serializer/test_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from unittest import TestCase
import sqlalchemy
from alcherializer import Serializer


class TestSerializerData(TestCase):

def test_data_single_instance(self) -> None:
class MyModel:
name = sqlalchemy.Column(sqlalchemy.String, nullable=False)

class MySerializer(Serializer):
class Meta:
model = MyModel

model = MyModel()
model.name = "hello world"

serializer = MySerializer(model)
self.assertDictEqual(serializer.data, {
"name": "hello world"
})

def test_data_multiple_instances(self) -> None:
class MyModel:
name = sqlalchemy.Column(sqlalchemy.String, nullable=False)

class MySerializer(Serializer):
class Meta:
model = MyModel

model = MyModel()
model.name = "hello world"

serializer = MySerializer([model], many=True)
self.assertListEqual(serializer.data, [
{"name": "hello world"}
])

0 comments on commit 65defb6

Please sign in to comment.