我定义了以下模型:
class Dictionary(Base):
key = Column()
value = Column()
class Attribute(Base):
id = Column()
name = Column()
class AttributeMap(Base):
objtype_id = Column()
attr_id = Column(foreign_keys='Attribute.id')
rel_attr = relationship('Attribute')
attr = association_proxy('rel_attr', 'name')
class AttributeValue(Base):
object_id = Column(foreign_keys='Object.id')
objtype_id = Column(foreign_keys='Object.objtype_id, AttributeMap.objtype_id')
attr_id = Column(foreign_keys='AttributeMap.attr_id')
uint_value = Column(foreign_keys='Dictionary.dict_key')
rel_attr = relationship('AttributeMap')
attr = association_proxy('rel_attr', 'attr')
rel_value = relationship('Dictionary')
value = association_proxy('rel_value', 'value')
class Object(Base):
id = Column()
objtype_id = Column(foreign_keys='Dictionary.dict_key')
rel_objtype = relationship('Dictionary')
objtype = association_proxy('rel_objtype', 'value')
rel_attributes = relationship('AttributeValue', collection_class=attribute_mapped_collection('attr'), uselist=True)
attributes = association_proxy('rel_attributes', 'value')
何时在单个事务期间创建Object类的实例并向属性集合添加新值。用法应该如下所示:
obj = Object()
obj.rel_objtype = 'Dictionary value'
obj.attributes['Attribute name'] = 'another Dictionary value'
将“字典值”分配给“obj.rel_objtype”应该会导致对现有字典属性的查询:
obj.objtype = 'Dictionary value'
# => obj.rel_objtype = Dictionary.query().filter(Dictionary.value == 'Dictionary value').one()
将“另一个字典值”分配给“obj.attributes”应该创建一个新的 AttributeValue 实例,其中“attr”=“属性名称”和“值”=“另一个字典值”:
av = AttributeValue()
obj.rel_attributes['Attribute name'] = av
av.attr = 'Attribute name'
# => av.rel_attr = AttributeMap.query().filter(AttributeMap.attr == 'AttributeName').one()
av.value = 'another Dictionary value'
# => av.rel_value => Dictionary.query().filter(DictionaryValue.value == 'another Dictionary value').one()
问题是 AttributeValue <-> AttributeMap 关系有两个外键:“attr_id”和“objtype_id”。我必须对 AttributeMap.query() 使用“objtype_id”以避免结果中出现重复条目,但是这个值只能从父“对象”实例中检索。
我该如何实施?