From 2e53be013f9fad489cea20769a5d14fb53882ec8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jacob=20St=C3=B6hr?= Date: Thu, 19 Dec 2019 17:27:28 +0100 Subject: [PATCH] Actually implement and test support for SQLAlchemy models. And minor readability improvements. --- serpy/serializer.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/serpy/serializer.py b/serpy/serializer.py index 692cf08..16e2e21 100644 --- a/serpy/serializer.py +++ b/serpy/serializer.py @@ -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 = {} @@ -85,8 +86,8 @@ 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( { @@ -94,8 +95,13 @@ def __new__(cls, name, bases, attrs): 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( {