Skip to content

Commit

Permalink
Merge pull request #73 from PrasanthChettri/exclude_to_dict
Browse files Browse the repository at this point in the history
added functionality to exclude columns after serialzation from to dict
  • Loading branch information
michaelbukachi authored May 18, 2021
2 parents c6b2059 + c8f6057 commit c92e21d
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 16 deletions.
10 changes: 5 additions & 5 deletions examples/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ class BaseModel(Base, SerializeMixin):

class User(BaseModel):
__tablename__ = 'user'

id = sa.Column(sa.Integer, primary_key=True)
password = sa.Column(sa.String)
name = sa.Column(sa.String)
posts = sa.orm.relationship('Post', backref='user')

Expand All @@ -34,7 +34,7 @@ class Post(BaseModel):

Base.metadata.create_all(engine)

bob = User(name='Bob')
bob = User(name='Bob' , password = "pass123")
session.add(bob)
session.flush()

Expand All @@ -46,17 +46,17 @@ class Post(BaseModel):
session.add(post2)
session.flush()

# {'id': 1, 'name': 'Bob'}
# {'id': 1, 'name': 'Bob' , 'password' : 'pass123'}
print(bob.to_dict())

# {'id': 1,
# 'name': 'Bob',
# 'posts': [{'body': 'Post 1', 'id': 1, 'user_id': 1},
# {'body': 'Post 2', 'id': 2, 'user_id': 1}]}
print(bob.to_dict(nested=True))
print(bob.to_dict(nested=True , exclude = ['password']))

# {'id': 1, 'body': 'Post 1', 'user_id': 1}
print(post1.to_dict())

# {'id': 2, 'body': 'Post 2', 'user_id': 1, 'user': {'id': 1, 'name': 'Bob'}}
# {'id': 2, 'body': 'Post 2', 'user_id': 1, 'user': {'id': 1, 'name': 'Bob' , 'password' : 'pass123'}}
print(post2.to_dict(nested=True))
10 changes: 8 additions & 2 deletions sqlalchemy_mixins/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class SerializeMixin(InspectionMixin):

__abstract__ = True

def to_dict(self, nested=False, hybrid_attributes=False):
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
:param nested: flag to return nested relationships' data if true
Expand All @@ -17,7 +17,13 @@ def to_dict(self, nested=False, hybrid_attributes=False):
:return: dict
"""
result = dict()
for key in self.columns:

if exclude is None:
view_cols = self.columns
else :
view_cols = filter(lambda e: e not in exclude, self.columns)

for key in view_cols :
result[key] = getattr(self, key)

if hybrid_attributes:
Expand Down
4 changes: 2 additions & 2 deletions sqlalchemy_mixins/serialize.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sqlalchemy_mixins.inspection import InspectionMixin

from typing import Optional , List

class SerializeMixin(InspectionMixin):

def to_dict(self, nested: bool = False, hybrid_attributes: bool = False) -> dict: ...
def to_dict(self, nested: bool = False, hybrid_attributes: bool = False, exclude: Optional[List[str]] = None) -> dict: ...
21 changes: 14 additions & 7 deletions sqlalchemy_mixins/tests/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class User(BaseModel):
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
posts = sa.orm.relationship('Post')
password = sa.Column(sa.String)

@hybrid_property
def posts_count(self):
Expand Down Expand Up @@ -62,11 +63,11 @@ def setUp(self):
self.session = Session(self.engine)
Base.metadata.create_all(self.engine)

user_1 = User(name='Bill u1', id=1)
user_1 = User(name='Bill u1', id=1 , password = 'pass1')
self.session.add(user_1)
self.session.commit()

user_2 = User(name='Alex u2', id=2)
user_2 = User(name='Alex u2', id=2 , password = 'pass2')
self.session.add(user_2)
self.session.commit()

Expand All @@ -93,15 +94,17 @@ def tearDown(self):
Base.metadata.drop_all(self.engine)

def test_serialize_single(self):
result = self.session.query(User).first().to_dict()
result = self.session.query(User)\
.first()\
.to_dict(exclude= ['password'])
expected = {
'id': 1,
'name': 'Bill u1'
}
self.assertDictEqual(result, expected)

def test_serialize_list(self):
result = [user.to_dict() for user in self.session.query(User).all()]
result = [user.to_dict(exclude = ['password']) for user in self.session.query(User).all()]
expected = [
{
'id': 1,
Expand All @@ -124,7 +127,8 @@ def test_serialize_nested(self):
'user_id': 1,
'user': {
'id': 1,
'name': 'Bill u1'
'name': 'Bill u1' ,
'password' : 'pass1'
},
'comments': [
{
Expand All @@ -139,7 +143,9 @@ def test_serialize_nested(self):
self.assertDictEqual(result, expected)

def test_serialize_single__with_hybrid(self):
result = self.session.query(User).first().to_dict(hybrid_attributes=True)
result = self.session.query(User)\
.first()\
.to_dict(hybrid_attributes=True , exclude = ['password'])
expected = {
'id': 1,
'name': 'Bill u1',
Expand All @@ -157,7 +163,8 @@ def test_serialize_nested__with_hybrid(self):
'user': {
'id': 1,
'name': 'Bill u1',
'posts_count': 1
'posts_count': 1 ,
'password' : 'pass1'
},
'comments': [
{
Expand Down

0 comments on commit c92e21d

Please sign in to comment.