class Video(BaseModel):
title = db.Column(db.String(100), nullable=True, comment="标题")
tags = db.relationship("Tag", secondary=tags, lazy='subquery',
backref=db.backref('videos', lazy=True))
class Tag(BaseModel):
"""
视频标签
"""
name = db.Column(db.String(100), nullable=False, comment="名称")
default_fields = ['id', 'name']
video_tag_table = db.Table('video_tag_table',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
db.Column('video_id', db.Integer, db.ForeignKey('video.id'), primary_key=True)
)
Video 和 Tag 多对多关系,查询用于某个tag_id 的视频有哪些,可以用:
query = Video.query.filter(Video.tags.any(Tag.id == tag_id))
https://stackoverflow.com/questions/40699642/how-to-query-many-to-many-sqlalchemy
如果你还想在中间表中定义其他字段,可以使用class来定义中间表,参考链接: https://www.michaelcho.me/article/many-to-many-relationships-in-sqlalchemy-models-flask
mini_qrcode=http://img.youbaokeji.cn/ikQmZvSjTVyaLDJHnBNt.jpg
关注公众号「Python之禅」,回复「1024」免费获取Python资源