간단한 읽기 전용 속성에 대해 매핑하는 방법을 파악하고 데이터베이스에 저장할 때 해당 속성이 실행되도록 설정하려고합니다.SQLAlchemy - 읽기 전용 (또는 계산 된) 속성에 대해 매핑하는 방법
인위적인 예는이 사실을 분명히해야합니다. 먼저, 간단한 테이블 :
meta = MetaData()
foo_table = Table('foo', meta,
Column('id', String(3), primary_key=True),
Column('description', String(64), nullable=False),
Column('calculated_value', Integer, nullable=False),
)
내가 내가여 session.commit를 (호출 할 때 나를 위해 calculated_value 컬럼에 삽입하는 읽기 전용 속성을 가진 클래스를 설정하고 싶은) ...
import datetime
def Foo(object):
def __init__(self, id, description):
self.id = id
self.description = description
@property
def calculated_value(self):
self._calculated_value = datetime.datetime.now().second + 10
return self._calculated_value
SQLAlchemy의 워드 프로세서에 따르면, 나는 내가 너무 좋아이지도를 가정하고 생각 :
이mapper(Foo, foo_table, properties = {
'calculated_value' : synonym('_calculated_value', map_column=True)
})
이의 문제가 _calculated_입니다 calculated_value 속성에 액세스 할 때까지 값은 None입니다. SQLAlchemy는 데이터베이스에 삽입 할 때 속성을 호출하지 않으므로 대신 None 값이 표시됩니다. "calculated_value"속성의 결과가 foo 테이블의 "calculated_value"열에 삽입되도록 매핑하는 올바른 방법은 무엇입니까?
확인 - 다른 사람이 같은 질문을하는 경우를 대비하여이 게시물을 편집 중입니다. 내가 마침내 MapperExtension을 사용했다.
class UpdatePropertiesExtension(MapperExtension):
def __init__(self, properties):
self.properties = properties
def _update_properties(self, instance):
# We simply need to access our read only property one time before it gets
# inserted into the database.
for property in self.properties:
getattr(instance, property)
def before_insert(self, mapper, connection, instance):
self._update_properties(instance)
def before_update(self, mapper, connection, instance):
self._update_properties(instance)
을 그리고 이것은 당신이 사용하는 방법입니다 : 나를 확장의 사용과 함께 당신에게 더 나은 예를 들어 보겠습니다. 데이터베이스에 삽입하기 전에 시작해야하는 몇 가지 읽기 전용 속성이있는 클래스가 있다고 가정 해 보겠습니다. 여기서는 읽기 전용 속성 각각에 대해 속성 값으로 채워지는 데이터베이스의 해당 열을 가지고 있다고 가정합니다. 당신은 여전히 각 속성에 대한 동의어를 설정하는거야,하지만 당신은 개체를 매핑 할 때 위의 매퍼 확장 사용
class Foo(object):
def __init__(self, id, description):
self.id = id
self.description = description
self.items = []
self.some_other_items = []
@property
def item_sum(self):
self._item_sum = 0
for item in self.items:
self._item_sum += item.some_value
return self._item_sum
@property
def some_other_property(self):
self._some_other_property = 0
.... code to generate _some_other_property on the fly....
return self._some_other_property
mapper(Foo, metadata,
extension = UpdatePropertiesExtension(['item_sum', 'some_other_property']),
properties = {
'item_sum' : synonym('_item_sum', map_column=True),
'some_other_property' : synonym('_some_other_property', map_column = True)
})
흥미 롭습니다.비록 내가 약간 다른 방식으로 이것을 해결했지만, 나는 그것이 작동해야하기 때문에 이것을 대답으로 표시했습니다. SQLAlchemy에 대해 더 많이 배울수록 더 좋아집니다! –