我定义了以下模型:
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 类的实例,并在单个事务期间向 attributes 集合添加新值。用法应如下所示:
obj = Object()
obj.rel_objtype = 'Dictionary value'
obj.attributes['Attribute name'] = 'another Dictionary value'
将“字典值”分配给“obj.rel_objtype”应导致查询现有的Dictionary属性:
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”。我必须使用“objtype_id”for AttributeMap.query()来避免结果中的重复条目,但是这个值只能从父“Object”实例中检索。
我该如何实现?