2011-11-27 121 views
1

SQLAlchemy新手(所以我的术语可能有点偏离)。我想在另一个构造函数内部创建一个数据库对象,但问题是我无法将所述对象添加到会话中,所以出现错误。SQLAlchemy - 在另一个实例中创建一个实例__init__

我的模式看起来有点像下面这样:

class Tag(Base): 
    __tablename__ = 'tag' 

    id = Column(Integer, Sequence('tag_id_seq'), primary_key=True, nullable=False) 
    type = Column(String(1), nullable=False) 
    name = Column(String(255), unique=True, nullable=False) 

    def __init__(self, type, name): 
     self.type=type 
     self.name=name 

    def __repr__(self): 
     return "<Tag('%s')>" % (self.id) 


class Venue: 
    __tablename__ = 'venue' 

    tag_id = Column(Integer) 
    tag_type = Column(String(1), nullable=False) 
    location = Column(String(255), nullable=False) 

    tag = ForeignKeyConstraint(
      (tag_id, tag_type), 
      (Tag.id, Tag.type), 
      onupdate='RESTRICT', 
      ondelete='RESTRICT', 
      ) 

    def __init__(self,name,location): 
     self.tag = Tag('V',name) 
     self.location = location 

当我做到以下几点:

session.add(Venue("Santa's Cafe","South Pole")) 

我得到一个错误:

UnmappedInstanceError: Class '__builtin__.instance' is not mapped 

我想这是因为在Venue的构造函数中创建的Tag对象不会添加到会话中。我的问题是如何/何时做到这一点。 (如果可能,我真的更喜欢在构造函数中创建该Tag对象)。我想我可以用scoped_session来做到这一点,但这似乎是一个非常糟糕的解决方案。

感谢

+3

不应该从会议地点继承基础? –

+0

是的。 (其他问题!) – DaedalusFall

回答

2
  1. 继承VenueBase。否则Venue将不会被映射。
  2. 移动ForeignKeyConstraint__table_args__
  3. 将当前无意义的tag替换为relationshipTag。默认值cascade参数relationship包含'save-update'规则,该规则会将新引用的对象添加到与父代相同的会话。

documentation:

save-update - cascade the Session.add() operation. This cascade applies both to future and past calls to add() , meaning new items added to a collection or scalar relationship get placed into the same session as that of the parent, and also applies to items which have been removed from this relationship but are still part of unflushed history.

+0

谢谢你,很好的解释。 stll习惯sqlalchemy告诉我什么是错的方式。 – DaedalusFall

相关问题