as_dict모든 클래스에 대한 메소드 를 얻기 위해 Ants Aasma가Mixin 설명하는 기술을 사용하는 클래스를 사용했습니다 .
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()
도움이 되었기를 바랍니다.
나는 이것으로 조금 더 놀아 보았고 실제로 관련 객체에 대한 링크가 dict있는 HAL 객체 의 형태로 인스턴스를 렌더링 해야했습니다. 그래서 저는 여기에이 작은 마법을 추가했습니다. 위와 같은 클래스의 모든 속성을 탐색 할 것입니다. 차이점은 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 정의에 사용했다고 속성 이름을 줄 것이다.