创建模型
https://www.cnblogs.com/chnmig/p/10446341.html
https://www.liaoxuefeng.com/wiki/897692888725344/955081460091040
#model.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index, and_, Table, Boolean, DateTime
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/jd?charset=utf8", max_overflow=5,encoding='utf-8')
Base = declarative_base()
class Goods(Base):
__tablename__ = 'goods'
id = Column(Integer, primary_key=True, autoincrement=True) #主键,自增
title = Column(String(512))
img = Column(String(1024))
price = Column(String(32))
sku = Column(String(32))
detail = Column(String(1024))
增
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from jd_models import Goods
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1/jd?charset=utf8", max_overflow=5)
session_maker = sessionmaker(bind=engine)
session = session_maker()
goods = Goods()
goods.title = title
goods.img = img
goods.price = price
goods.sku = sku
goods.detail = detail
session.add(goods)
session.commit()
查
good = session.query(Goods).filter_by(id=5).all()
goods = session.query(Goods).filter(and_(Goods.id>1, Goods.id<10)).all()
print(good[0].__dict__)
创建一对多模型
class Goods(Base):
__tablename__ = 'goods'
id = Column(Integer, primary_key=True, autoincrement=True) #主键,自增
title = Column(String(512))
img = Column(String(1024))
price = Column(String(32))
sku = Column(String(32))
detail = Column(String(1024))
product_id = Column(Integer, ForeignKey('product.id'), nullable=False)
class Product(Base):
__tablename__ = 'product'
id = Column(Integer, primary_key=True, autoincrement=True)
product_name = Column(String(128), nullable=False, unique=True)
good = relationship('Goods', backref='product')
创建多对多模型
class Student(Base):
__tablename__ = 'studnet'
id = Column(Integer, primary_key=True, autoincrement=True)
s_name = Column(String(5), unique=True, nullable=False)
s_age = Column(Integer, default=20)
s_gender = Column(Boolean, default=1)
creat_time = Column(DateTime, default=datetime.now)
s_c = Table('s_c', Column('s_id', Integer, ForeignKey('studnet.id')),Column('c_id', Integer, ForeignKey('course.id')))
class Course(Base):
id = Column(Integer, primary_key=True, autoincrement=True)
c_name = Column(String(10), unique=True, nullable=True)
stu = relationship('Student', secondary=s_c, backref='cou')
网友评论