【问题标题】:SQLAlchemy: How to save an object with the foreign key?SQLAlchemy:如何使用外键保存对象?
【发布时间】:2013-03-10 14:51:33
【问题描述】:

我有这些课程。

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?

【问题讨论】:

    标签: foreign-keys sqlalchemy flask flask-sqlalchemy


    【解决方案1】:

    buoy.author_id 将在 buoy 实例添加到会话并调用 session.flush() 后设置。

    【讨论】:

    • buoy = Buoy(label, lead, body, current_user) db_session.add(buoy) db_session.commit() where db_session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine) ) 但它仍然不起作用 :( 我的意思是我的数据库中的 author_id 列中没有值。
    • author 是否也添加到会话中(并已提交)?
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2022-10-02
    • 2018-04-28
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多