传统SQLalchemy写法
联合外键约束:
from sqlalchemy import Integer, ForeignKey, ForeignKeyConstraint
mytable = Table(
"mytable", meta,
Column("user_id", Integer, ForeignKey("customers.customer_id")),
Column("post_id", Integer),
ForeignKeyConstraint(["user_id", "post_id"], ["user.id", "post.id"])
)
联合唯一约束:
from sqlalchemy import Integer, ForeignKey, UniqueConstraint
mytable = Table(
"mytable", meta,
Column("user_id", Integer),
Column("post_id", Integer),
UniqueConstraint("user_id", "post_id")
)
SQLAlchemy ORM写法:
orm写法这边通过__table_args_
_传递表级约束
联合外键约束:
from datetime import datetime
from core import db
from sqlalchemy import ForeignKey, ForeignKeyConstraint
from sqlalchemy.dialects.mysql import INTEGER, DATETIME
__all__ = ("UserHistory",)
class UserHistory(db.Model):
"""
用户浏览历史表
用于储存用户浏览历史数据
"""
__table_name__ = "user_info"
__table_args__ = (ForeignKeyConstraint(["user_id", "post_id"], ["user.id", "post.id"]),)
# 全局ID 自增
id = db.Column(INTEGER, index=True, primary_key=True, autoincrement=True, nullable=False)
# 用户ID 外键
user_id = db.Column(INTEGER, ForeignKey("user_info.id"))
# 资讯Id 外键
post_id = db.Column(INTEGER, ForeignKey("spider_origin_post_data.id"))
# 浏览时间
time = db.Column(DATETIME, nullable=False)
联合唯一约束:
from datetime import datetime
from ..core import db
from sqlalchemy import ForeignKey, UniqueConstraint
from sqlalchemy.dialects.mysql import INTEGER, DATETIME
__all__ = ("UserHistory",)
class UserHistory(db.Model):
"""
用户浏览历史表
用于储存用户浏览历史数据
"""
__table_name__ = "user_info"
__table_args__ = (UniqueConstraint("user_id", "post_id"),)
# 全局ID 自增
id = db.Column(INTEGER, index=True, primary_key=True, autoincrement=True, nullable=False)
# 用户ID 外键
user_id = db.Column(INTEGER, ForeignKey("user_info.id"))
# 资讯Id 外键
post_id = db.Column(INTEGER, ForeignKey("spider_origin_post_data.id"))
# 浏览时间
time = db.Column(DATETIME, nullable=False)
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
凤曦的小窝
本文地址: Flask SQLAlchemy 设置联合唯一约束/联合外键约束
本文地址: Flask SQLAlchemy 设置联合唯一约束/联合外键约束