SQLalchemy 事务未按预期工作

Sqlalchemy transaction not working as expected

我阅读了有关 transactions automatically determine which objects are to be saved first when objects have relations

的 sqlalchemy 事务

但是当我尝试时

>> user = User('demo user')
>> post = Post('Sample post')
>> post.user_id = user.id
>> db.session.add_all([post, user])
>> db.session.commit()

它用 user_id = None 创建了新的 post,这不是预期的。

下面是我的模型实现

class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(40),nullable=False, unique=True, index=True)
    posts = db.relationship(
        'Post',
        backref='user',
        lazy='dynamic'
    )

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

    def __repr__(self):
        return f'<User {self.username}>'



class Post(db.Model):

    __tablename__ = 'posts'

    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(50), index=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('users.id'))
    date = db.Column(db.DateTime(), default=datetime.datetime.now)

    def __init__(self, title):
        self.title = title

    def __repr__(self):
        return f'<Post {self.title}>'

有人可以解释为什么交易没有节省 user_id 价值吗?

您遇到的问题是因为 id 是提交后由数据库生成的。所以赋值时(post.user_id=user.id)user.id就是None.

如果在 user 对象上将 post 附加到 posts SQLAlchemy 会处理添加正确的 id.

user = User('demo user')
post = Post('Sample post')
user.posts.append(post)
db.session.add(user)
db.session.commit()