flask-19Flask-SQLAlchemy多对多(many-to-many)关系⽬录
如果您想要⽤多对多关系,您需要定义⼀个⽤于关系的辅助表。对于这个辅助表, 强烈建议 不 使⽤模型,⽽是采⽤⼀个实际的表:
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
db.Column('page_id', db.Integer, db.ForeignKey('page.id'))
)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags,
backref=db.backref('pages', lazy='dynamic'))
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
这⾥我们配置 Page.tags 加载后作为标签的列表,因为我们并不期望每页出现太多的标签。⽽每个 tag 的页⾯列表( Tag.pages)是⼀个动态的反向引⽤。 正如上⾯提到的,这意味着您会得到⼀个可以发起 select 的查询对象。
在教程
基础下实现
⼀、模型创建
1、apps下创建goods
2、apps/goods下创建models.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/17 17:23
# @Author  : niubobo
# @File    : models.py
# @Software: PyCharm
from datetime import datetime
from ext import db
class Goods(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
gname = db.Column(db.String(100), nullable=False)
price = db.Column(db.Float, nullable=False)
def __str__(self):
ame
# 关系表
class User_goods(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
good_id = db.Column(db.Integer, db.ForeignKey('goods.id'), nullable=False)
number = db.Column(db.Integer, default=1)
3、修改app.py
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from apps import create_app
from ext import db
from dels import User
from dels import Article
ds.models import *
app = create_app()
print(app)
manager = Manager(app=app)
# 命令⼯具
migrate = Migrate(app=app, db=db)
# 添加命令到manager
manager.add_command('db', MigrateCommand)
@managermand
def init():
print('初始化')
if __name__ == '__main__':
manager.run()
4、⽣成模型库表
终端输⼊命令执⾏:
python app.py db migrate
python app.py db upgrade
5、做⼀点数据在数据库当中执⾏脚本
insert into `goods` (`gname`, `price`) values('⼿机','5899');
insert into `goods` (`gname`, `price`) values('笔记本','9999');
insert into `goods` (`gname`, `price`) values('⽿机','199');
insert into `goods` (`gname`, `price`) values('⼿环','399');
insert into `goods` (`gname`, `price`) values('键盘','499');
insert into `goods` (`gname`, `price`) values('⿏标','99');
⼆、应⽤(商城例⼦)
1、在apps/goods下创建view.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/17 17:51
# @Author  : niubobo
# @File    : view.py
# @Software: PyCharm
from flask import Blueprint, request, render_template, redirect, url_for
from sqlalchemy import or_, and_
ds.models import Goods, User_goods
from dels import User
from ext import db
goods_bp = Blueprint('goods', __name__)
# ⽤户商品(xxx⽤户买了哪些商品)
@ute('/findgoods')
def find_goods():
pass
# 根据商品⽤户(xxx商品哪些⼈买了)
@ute('/finduser')
def find_user():
pass
# 商品展⽰列表
@ute('/show')
def show():
users = User.query.filter(User.isdelete == False).all()
goods_list = Goods.query.all()
return  render_template('goods/show.html', users=users,goods_list=goods_list)
# ⽤户购买商品
@ute('/buy')
def buy():
uid = ('uid')
gid = ('gid')
ug = User_goods()
ug.user_id = uid
db.session.add(ug)
db.sessionmit()
return  redirect(url_for('goods.show'))
2、修改apps下__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/17 13:05
# @Author  : niubobo
# @File    : __init__.py.py
# @Software: PyCharm
from flask import Flask
import settings
from apps.article.view import article_bp
ds.view import goods_bp
from apps.user.view import user_bp
from ext import db
def create_app():
app = Flask(__name__, template_folder='../templates', static_folder='../static')    # 加载配置
# 将db对象与app进⾏关联
db.init_app(app=app)
# 蓝图 ,将蓝图对象绑定到app上
return app
if __name__ == '__main__':
app = create_app()
app.run()
3、templates下新增goods⽂件夹
4、templates/goods下新增show.html
{% extends 'base.html' %}
{% block title %}
购物界⾯
{% endblock %}
{% block jquery %}
<script src="cdn.bootcdn/ajax/libs/jquery/3.1.0/jquery.min.js"></script> {% endblock %}
{% block middle %}
<form action="{{ url_for('ister') }}" method="post">
<p>
<select name="uid">
<option value="0">请选择购物⽤户--必须选⼀个</option>
{% for user in users %}
<option value="{{ user.id }}">{{ user.username }}</option>
{% endfor %}
</select>
</p>
<p>
<table border="1" cellspacing="0" width="50%">
<tr>
<th>序号</th>
<th>商品名</th>
<th>价格</th>
<th>操作</th>
</tr>
{% for goods in goods_list %}
<tr>
<td>{{ loop.index }}</td>
<td>{{ ame }}</td>
<td>{{ goods.price }}</td>
<td>
<input type="button" class="btnbuy" value="购买" tag="{{ goods.id }}"/>
</td>
</tr>
{% endfor %}
</table>
</p>
</form>
flask下载
{% endblock %}
{% block myjs %}
<script>
//购买
$('.btnbuy').click(function () {
goods_id = $(this).attr('tag');
user_id = $("select[name='uid']").val();
console.log(goods_id,user_id) // 可以注释掉
location.href = '{{ url_for('goods.buy') }}?uid='+user_id+'&gid='+goods_id;
// ip:端⼝/search?search=输⼊的值
})
</script>
{% endblock %}
5、base.html添加商城验证购买逻辑

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。