为了获得as_dict
我所有班级的方法,我使用了一个Mixin
使用Ants Aasma描述的技术的班级。
class BaseMixin(object):
def as_dict(self):
result = {}
for prop in class_mapper(self.__class__).iterate_properties:
if isinstance(prop, ColumnProperty):
result[prop.key] = getattr(self, prop.key)
return result
然后在课堂上像这样使用它
class MyClass(BaseMixin, Base):
pass
这样,您可以在的实例上调用以下内容MyClass
。
> myclass = MyClass()
> myclass.as_dict()
希望这可以帮助。
我对此进行了进一步的研究,实际上我需要将实例渲染为HAL对象dict
的形式,并带有指向相关对象的链接。因此,我在这里添加了这个小技巧,它将覆盖与上述相同的类的所有属性,不同之处在于,我将更深入地搜索属性并自动生成这些属性。Relaionship
links
请注意,这仅适用于具有单个主键的关系
from sqlalchemy.orm import class_mapper, ColumnProperty
from functools import reduce
def deepgetattr(obj, attr):
"""Recurses through an attribute chain to get the ultimate value."""
return reduce(getattr, attr.split('.'), obj)
class BaseMixin(object):
def as_dict(self):
IgnoreInstrumented = (
InstrumentedList, InstrumentedDict, InstrumentedSet
)
result = {}
for prop in class_mapper(self.__class__).iterate_properties:
if isinstance(getattr(self, prop.key), IgnoreInstrumented):
# All reverse relations are assigned to each related instances
# we don't need to link these, so we skip
continue
if isinstance(prop, ColumnProperty):
# Add simple property to the dictionary with its value
result[prop.key] = getattr(self, prop.key)
if isinstance(prop, RelationshipProperty):
# Construct links relaions
if 'links' not in result:
result['links'] = {}
# Get value using nested class keys
value = (
deepgetattr(
self, prop.key + "." + prop.mapper.primary_key[0].key
)
)
result['links'][prop.key] = {}
result['links'][prop.key]['href'] = (
"/{}/{}".format(prop.key, value)
)
return result
__table__.columns
将为您提供SQL字段名称,而不是您在ORM定义中使用的属性名称(如果两者不同)。