SQLAlchemy:如何使用外键保存对象?

时间:2013-03-21 07:27:16

标签: foreign-keys sqlalchemy flask flask-sqlalchemy

我有这些课程。

class User(object):

    query = db_session.query_property()        

    def __init__(self, username, passhash, salt):    
        self.username = username    
        self.passhash = passhash    
        self.salt = salt

users = Table('users', metadata,    
    Column('id', Integer, primary_key=True),    
    Column('username', String(60)),    
    Column('passhash', String),    
    Column('salt', String)    
    )

mapper(User, users)

class Buoy(object):

    query = db_session.query_property()    
    author = relationship("User", backref=backref("buoys", order_by=id))

    def __init__(self, label, lead, body, author):    
        self.label = label    
        self.lead = lead    
        self.body = body    
        self.author = author

buoys = Table('buoys', metadata,    
    Column('id', Integer, primary_key=True),    
    Column('label', String),    
    Column('lead', String),    
    Column('body', String),    
    Column('author_id', Integer, ForeignKey('users.id'))    
    )

mapper(Buoy, buoys)

在我的Python Flask代码中,我想创建并保存一个新的浮标:

buoy = Buoy(label, lead, body, current_user)

当我这样做时,buoy.author是正确的但是buoy.author_id是None。请问,当buoy.author已知时,如何自动将current_user.id分配给buoy.author_id?

1 个答案:

答案 0 :(得分:2)

buoy.author_id实例添加到会话并调用buoy后,将设置

session.flush()