实体 - (多对一) - > related-table - (多对一) - >属性映射不起作用

时间:2012-01-30 14:26:18

标签: python sqlalchemy

我在一个相当简单的情况下有映射问题。有人可以帮忙吗? 以下是DTO:

class AttributeDTO(object):
    id = None
    name = None

class RelationDTO(object):
    id = None
    name = None
    attribute = None # one attribute per relation

class EntityDTO(object):
    id = None
    name = None

    relation = None
    #it works fine, but then I must get myEnt.relation.attribute, 
    #when i want to get the attribute from entity

    attribute = None # I want it to be placed HERE!

以下是地图制作者:

class TableMapper(object):

    def __init__(self, metadata, mapped_type):
        self._table = None
        self._mapped_type = mapped_type

    def get_table(self):
        return self._table

    def set_table(self, table):
        self._table = table

    def map_table(self):
        mapper(self._mapped_type, self._table)
        return self._table

class AttributeTableMapper(TableMapper):
    ...

class RelationTableMapper(TableMapper):
    ...
    def map_table(self, attribute_table):
        r_attribute = relationship(AttributeDTO, 
            uselist = False, remote_side = [attribute_table.c.id])
    mapper(RelationDTO, 
           self._table, 
           properties = {'attribute': r_attribute})
    return self._table

class EntityTableMapper(TableMapper):

    def __init__(self, metadata):
        TableMapper.__init__(self, metadata, EntityDTO)
        self.set_table(Table('entities', metadata,
                         Column('id', Integer, ...)))

    def map_table(self, relation_table, attribute_table):
        r_attribute = relationship(AtributeDTO, uselist = False, 
#I TRIED THE FOLLOWING, BUT GOT ERRORS
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            primaryjoin = self._table.c.id_relation == relation.c.id,
            secondary = relation_table,
            secondaryjoin = relation_table.c.id_attribute == attribute_table.c.id)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        mapper(EntityDTO, self._table, properties={'attribute': r_attribute})
        return self._table

所以,我映射表格:

attribute_t_mapper = AttributeTableMapper(self._metadata)
relation_table = RelationTableMapper(self._metadata).\
    map_table(attribute_t_mapper.get_table())
attribute_table = attribute_t_mapper.map_table()
entity_table = EntityTableMapper(self._metadata).\
    map_table(relation_table, attribute_table)

并尝试从实体获取我的属性:

entity = session.query(EntityDTO).first() #OK!
a = entity.relation.attribute #OK!
a = entity.attribute #ERROR!

sqlalchemy.orm.exc.UnmappedColumnError:没有在mapper Mapper | EntityDTO |实体上配置列relation.id ...

我做错了什么?

0 个答案:

没有答案