附加到sqlalchemy

时间:2015-05-18 10:03:54

标签: python sqlalchemy

我有许多经典的孩子,一个父母的问题。我尝试将子项添加到现有父项,而不将父项重写到我的数据库中:

def insert_symbol(self, name, group, internal):
    # get the parent object, insert if not existent
    group = self.insert_group(group)

    # append to list of childs in this parent
    group.symbols.append(Symbol(name=name, internal=internal))

    # child is correct!
    print group.symbols[0]

    # nothing in here?!
    print self.__session.dirty
    # nothing to commit?!
    self.__session.commit()

这里列出了关系的定义:

class Group(Base):
    __tablename__ = 'assets_symbolgroup'                                                                                       

    id = Column(Integer, primary_key=True, autoincrement=True)                                                                 
    name = Column(String(100), unique=True, nullable=False)                                                                    
    symbols = relationship("Symbol", backref="group")

    def __repr__(self):                                                                                                        
        return "<Group(name='{0}')>".format(self.name)                                                                         


class Symbol(Base):                                                                                                            
    __tablename__ = 'assets_symbol'                                                                                            

    id = Column(Integer, primary_key=True, autoincrement=True)                                                                 
    name = Column(String(100), unique=True, nullable=False)                                                                    
    group_id = Column(Integer, ForeignKey('assets_symbolgroup.id'), nullable=False)
    alive = Column(BOOLEAN, default=True, nullable=False)                                                                      
    internal = Column(String(100))                                                                                             

    @property
    def summary(self):
        return {"name": self.name, "group": self.group.name, "internal": self.internal}

    def __repr__(self):                                                                                                        
        return "<Asset(name='{0}', group='{1}')>".format(self.name, self.group)                   

在没有重写父母的情况下添加孩子的最佳方式是什么?

感谢您的帮助 托马斯

0 个答案:

没有答案