在SQLalchemy中设置值之后,如何约束以不变的限制
我现在有以下模型
class Card(Base):
__tablename__ = 'Cards'
__table_args__ = (
db.Index(
'one_active_code_only',
'code', 'company',
unique=True,
postgresql_where='used_by is NULL'
),
db.CheckConstraint(
'(used_by IS NULL AND used_at IS NULL) OR (used_by IS NOT NULL AND used_at IS NOT NULL)',
name='used_by and used_at must be set together'
),
db.CheckConstraint(
'(booked_by IS NULL AND booked_at IS NULL) OR (booked_by IS NOT NULL AND booked_at IS NOT NULL)',
name='booked_by and booked_by must be set together'
),
)
name = db.Column(db.String(100), nullable=False)
code = db.Column(db.String(100), nullable=False)
value = db.Column(db.Numeric, nullable=False)
company = db.Column(db.ForeignKey('Companies.id'), nullable=False)
img = db.Column(db.String, nullable=True)
booked_at = db.Column(db.DateTime, nullable=True)
booked_by = db.Column(db.ForeignKey('Users.id'), nullable=True)
used_at = db.Column(db.DateTime, nullable=True)
used_by = db.Column(db.ForeignKey('Users.id'), nullable=True)
,我想要约束used_by
booked_by 在第一个值集之后无法改变。
我该如何实现?
我不想在服务器中实现之前的问题
机制,我想直接在数据库中实现它,以防止从另一个数据库客户端更改数据。
需求.txt
Flask==2.1.1
Flask-SQLAlchemy==2.5.1
SQLAlchemy==1.4.35
...
...
...
I have the following model
class Card(Base):
__tablename__ = 'Cards'
__table_args__ = (
db.Index(
'one_active_code_only',
'code', 'company',
unique=True,
postgresql_where='used_by is NULL'
),
db.CheckConstraint(
'(used_by IS NULL AND used_at IS NULL) OR (used_by IS NOT NULL AND used_at IS NOT NULL)',
name='used_by and used_at must be set together'
),
db.CheckConstraint(
'(booked_by IS NULL AND booked_at IS NULL) OR (booked_by IS NOT NULL AND booked_at IS NOT NULL)',
name='booked_by and booked_by must be set together'
),
)
name = db.Column(db.String(100), nullable=False)
code = db.Column(db.String(100), nullable=False)
value = db.Column(db.Numeric, nullable=False)
company = db.Column(db.ForeignKey('Companies.id'), nullable=False)
img = db.Column(db.String, nullable=True)
booked_at = db.Column(db.DateTime, nullable=True)
booked_by = db.Column(db.ForeignKey('Users.id'), nullable=True)
used_at = db.Column(db.DateTime, nullable=True)
used_by = db.Column(db.ForeignKey('Users.id'), nullable=True)
Now I want constraints used_by
and booked_by
to be unchangeable after the first value set.
How can I achieve that?
I don't want to implement the before-query
mechanism in the server, I want to implement it within the database directly, to prevent changing data from another database client.
requirements.txt
Flask==2.1.1
Flask-SQLAlchemy==2.5.1
SQLAlchemy==1.4.35
...
...
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论