Flask's ORM detailed instructions

ORM

ORM (Object Relational Mapping) is called object-relational mapping. It maps a class to a table in the database and maps attributes to columns in the database table. Each instance object corresponds to a row of data in the database table.

Install Flask-SQLAlchemy

pip install flask-sqlalchemy

create model

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"

db = SQLAlchemy(app)


class Category(db.Model):
    __tablename__ = "t_category"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

db.create_all()

__tablename__The attribute defines the table name, which defaults to the class name, __tablename_zh__indicating the Chinese name of the table structure.
__table_desc__The attribute definition table describes the content.
db.create_all()Used to create all table structures.

Database Connectivity

SQLALCHEMY_DATABASE_URIDefine the database information that needs to be connected, and other commonly used database configurations:

database connection address
MySQL mysql+pymysql://username:password@host:3306/database name
SQL mssql+pymssql://username:password@host:port/database name
Oracle oracle+cx_oracle://username:password@host:1521/SID name
SQLite sqlite:///filename
Create data type of Model field
field name type illustrate
Integer int Ordinary integer, usually 32 bits
SmallInteger int An integer with a small value range, usually 16 bits
BigInteger int or long Integer with unlimited precision
Float float floating point number
Double float double precision floating point
Numeric decimal.Decimal Fixed-point number (default decimal.Decimal, convert to float when asdecimal=False)
String string variable length string
Text string Programming strings, optimized for longer or unlimited length strings, for long text
Boolean bool Boolean value
Date datetime.date date only
Time datetime.time time only
DateTime datetime.datetime date and time
Interval datetime.timedelta time interval
Enum Enum enumerated type
ARRAY array array
PickType any python object Automatic serialization using Pickle
Unicode unicode variable-length Unicode string
UnicodeText unicode Variable-length Unicode strings, optimized for longer or unlimited-length strings
LargeBinary binary large binary byte data
Optional addition options for field descriptions
Attributes illustrate
primary_key primary key
default Defaults
unique Is it unique
nullable Is it allowed to be empty
index Whether to add as an index
autoincrement self-increment
comment note
one-to-many relationship
class Post(db.Model):
  id = db.Column(db.Integer(),primary_key=True)
    title = db.Column(db.String(255))
  text = db.Column(db.Text())
  publish_date = db.Column(db.DateTime())
  user_id = db.Column(db.Integer(),db.ForeignKey('user.id'))


class User(db.Model):
  id = db.Column(db.Integer(),primary_key=True)
  username = db.Column(db.String(255))
  password = db.Column(db.String(255))
  posts = db.relationship('Post',backref='user',lazy='dynamic')

注意:
1. The parameter passed to db.ForeignKey is a string used to represent the id column of the user table. If __tablename__ is used to customize the table name in the user table, you need to use the custom table name 2. "Multiple
" The side of "one" writes ForeignKey, and the side of "one" can be read and modified through the table name. (the backref of the side of "one"). The relationship can be on either side, usually on the "one" side.

lazy关键字说明:lazy 决定了 SQLAlchemy 什么时候从数据库中加载数据。
Optional values:
select: (default) When the properties of the object are read, all properties will be loaded.
dynamic: Returns a query object, and all data will be loaded only when the method of the object is executed. Such as: all()
joined: join operation is performed on the two associated tables, so as to obtain all related objects

many-to-many relationship
t_user_role = db.Table("t_user_role",
    db.Column("user_id", db.Integer, db.ForeignKey("t_user.id"), primary_key=True),
    db.Column("role_id", db.Integer, db.ForeignKey("t_role.id"), primary_key=True)
)


class User(db.Model):
    __tablename__ = "t_user"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(15))
    roles = db.relationship("Role", backref="users", secondary=t_user_role)


class Role(db.Model):
    __tablename__ = "t_role"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(15))

Add

u = User(name="张三")
db.session.add(u)

# 对于多对对关系
r1 = Role(name="Admin")
r2 = Role(name="User")
db.session.add(r1)
db.session.add(r2)
u.roles = [r1,r2]
db.session.add(u)

# 也可以使用这个方式
u.roles.append(r1)
u.roles.append(r2)
db.session.commit()
delete
c = Category.query.get(1)
db.session.delete(c)
batch deletion
# 方法一
posts = Posts.query.filter(User.user_id ==1).all()
for p in posts:
	db.session.delete(p)
db.session.commit()

#方法二
Posts.query.filter(User.user_id==1).delete(synchronize_session=False)
db.session.commit()

The above deletion operations are all logical deletions, so delete them carefully!

Revise
p = Posts.query.get(1)
p.title = "Python"
db.session.add(p)
db.session.commit()

Pending supplementary query operation. . .

Guess you like

Origin blog.csdn.net/qq_42349944/article/details/130487557