Flask Python Flask-SQLAlchemy中数据库的数据类型、flask中数据可的列约束配置
SQLAlchemy官方文档地址
实战的代码分享
Flask-SQLAlchemy框架为创建数据库的实例提供了一个基类及一系列辅助类和辅助函数,用于定于数据库模型的结构,如下:
c
from project.extension import db
from datetime import datetime
from typing import List
from sqlalchemy import Integer, String, DateTime, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from project.personal.model import User
#资源内容模型
class Resource(db.Model): # 所有的数据库模型均继承自 db.Model 类
__tablename__ = 'resource_copy1' # 一般会指定表名,虽然有默认机制,但不一定是我们想要的结果
id: Mapped[int] = mapped_column(Integer, primary_key=True, nullable=False, autoincrement=True) # 类变量代表表的列名
r_type: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
dept_id: Mapped[int] = mapped_column(Integer, nullable=False)
title: Mapped[str] = mapped_column(String(50), nullable=False)
published_time: Mapped[str] = mapped_column(String(50), nullable=False)
publisher_book_name: Mapped[str] = mapped_column(String(50))
like_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
view_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
content: Mapped[str] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now, onupdate=datetime.now)
deptss: Mapped['Dept'] = relationship('Dept', foreign_keys=[dept_id],
primaryjoin='Dept.id == Resource.dept_id')
# id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
# r_type = db.Column(db.INTEGER, default=0, comment='resource type 0 文献 1 指南 2 大会')
# is_show = db.Column(db.INTEGER, default=0, comment='是否上架 0 未上架 1 上架')
# title = db.Column(db.String(40))
# desc = db.Column(db.TEXT)
# cover = db.Column(db.String(40))
# published_time = db.Column(db.String(40))
# content = db.Column(db.TEXT)
# file_path = db.Column(db.String(128))
# origin_link = db.Column(db.String(128))
# view_count = db.Column(db.INTEGER)
# like_count = db.Column(db.INTEGER)
# collect_count = db.Column(db.INTEGER)
# file_size = db.Column(db.String(40))
# publisher_book_name = db.Column(db.String(40))
# resource_type_id = db.Column(db.INTEGER)
def to_format(self):
return {
"id": self.id,
"title": self.title,
"published_time": self.published_time,
"view_count": self.view_count,
"publisher_book_name": self.publisher_book_name,
"dept_name": self.deptss.name,
"dept_en_name": self.deptss.english_name
}
def __init__(self, title, r_type):
self.title = title
self.r_type = r_type
# 用于输出该类的对象被print()时输出的字符串
def __repr__(self) -> str:
return f'<Resource id={self.id} title={self.title} r_type={self.r_type}>'
数据类型
SQLAlchemy中基本包含了所有数据库中的类型:
除了列数据类型的设置,还需要对列约束进行相关配置
列约束配置
SQLAlchemy常用列约束:
自定义方法
这里分享了模型关联的实现,在最后介绍了为啥要在每个model类中增加自定义方法,点击去查看
其中:在每个model类里都定义了to_format()
方法,这个是因为我要将数据返回给前端,一是只展示需要的数据,二是格式需要是json格式才能返回,所以直接在这里定义了处理方法,