SQLAlchemy Constraints

本文探讨了数据完整性的重要性,强调了如何通过列约束确保数据的一致性和准确性。列约束用于强制实施一致性规则,如非空和唯一性,防止无效数据如负价格插入数据库。在SQLAlchemy中,这些约束可以通过db.Column()设置。例如,User模型中的name列为非空,title列为唯一;Product模型中设定了检查约束,确保价格始终大于0。这些约束保障了数据库的准确性和一致性。
摘要由CSDN通过智能技术生成

Data integrity is concerned with storing data accurately, ensuring that if a row should not have an empty name that we don’t store it in the database, or that we don’t store a negative price value or any number of same constraints like that.

Column constraints ensure that we apply rules of consistency and validation consistently. That means that if one record has certain rules that make it valid, then we should apply those rules to all records and all changes that are sent to the database, treating all rules of consistency for all records the same.

  • Column constraints ensure data integrity across our database, allowing for database accuracy and consistency.
  • Constraints are conditions on your column, that provide checks on the data’s validity. It does not allow data that violates constraints to be inserted into the database (it will raise an error if you attempt to).
  • In SQLAlchemy, constraints are set in db.Column() after setting the data type.
    • nullable=False is equivalent to NOT NULL in SQL
    • unique=True is equivalent to UNIQUE in SQL
# 例子
class User(db.Model):
	name = db.Column(db.String(), nullable=False)
	title = db.Column(db.String(), unique=True)
	title = db.Column(db.String(), unique=True, nullable=False)

Implement a check constraint

class Product(db.Model):
	# This ensures that no product goes into the table with a nonpositive price value
	price = db.Column(db.Float, db.CheckConstraint('price>0'))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值