Skip to content

Commit

Permalink
Actually implement and test support for SQLAlchemy models.
Browse files Browse the repository at this point in the history
And minor readability improvements.
  • Loading branch information
jacobstoehr committed Dec 19, 2019
1 parent 9c5e9fa commit 2e53be0
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions serpy/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def _get_list_of_fields(model_fields, fields, exclude):
if field.name not in exclude
]
return fields

def __new__(cls, name, bases, attrs):
# Fields declared directly on the class.
direct_fields = {}
Expand Down Expand Up @@ -85,17 +86,22 @@ def __new__(cls, name, bases, attrs):
raise RuntimeError(
'`fields` and `exclude` prohibit each other.'
)
if getattr(model, "_meta", None):
# Django models
# Django models
if getattr(model, '_meta', None) is not None:
fields = cls._get_list_of_fields(model._meta.fields, fields, exclude)
direct_fields.update(
{
field.name: Field()
for field in fields
}
)
elif getattr(model, "__table__", None):
# SQLAlchemy model
# SQLAlchemy model
# This has to be like this because SQLAlchemy has not implemented
# __bool__, so we cannot compare it with a simple
# `getattr(mode, '__table'__, None) is not None`. Instead, check if
# the getattr returned `None`, if yes, that would be an instance of
# `None`, so we can say that this is not an SQLAlchemy model.
elif not isinstance(getattr(model, '__table__', None), type(None)):
fields = cls._get_list_of_fields(model.__table__.columns, fields, exclude)
direct_fields.update(
{
Expand Down

0 comments on commit 2e53be0

Please sign in to comment.