gpt4 book ai didi

foreign-keys - SQLAlchemy:如何用外键保存对象?

转载 作者:行者123 更新时间:2023-12-03 17:36:45 27 4
gpt4 key购买 nike

我有这些类(class)。

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?

最佳答案

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

关于foreign-keys - SQLAlchemy:如何用外键保存对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15541703/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com