Flask 入门(九)
外键数据库
我们想想,所有的数据不可能这么简单,万一建的数据库有了外键呢?如何增加,如何查询?
承接上文:
先登录mysql数据库,把里面的表和数据都删了
执行语句:
use data
select * from users
select * from dogs
发现是空的
然后修改main.py中的代码如下:
#encoding:utf-8
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:005@127.0.0.1:3306/data'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
app.config['JSON_AS_ASCII']=False
db = SQLAlchemy(app)
db = SQLAlchemy(use_native_unicode='utf8')
class Users(db.Model):
__tablename__='users'
id=db.Column(db.Integer,primary_key=True,autoincrement=True)
name=db.Column(db.String(20),nullable=False)
class Dogs(db.Model):
__tablename__='dogs'
id=db.Column(db.Integer,primary_key=True,autoincrement=True)
name=db.Column(db.String(20),nullable=False)
master_id=db.Column(db.Integer,db.ForeignKey('users.id'))
@app.route('/')
def index():
db.create_all()
return '欢迎登录'
@app.route('/adduser/')
def addusers():
user1=Users(name='huhai')
user2=Users(name='lanyue')
db.session.add(user1)
db.session.add(user2)
db.session.commit()
return '添加成功!'
@app.route('/adddogs/')
def adddogs():
dog1=Dogs(name='gou1',master_id=1)
dog2=Dogs(name='gou2',master_id=2)
dog3=Dogs(name="gou2",master_id=1)
dog4=Dogs(name="gou1",master_id=2)
db.session.add(dog1)
db.session.add(dog2)
db.session.add(dog3)
db.session.add(dog4)
db.session.commit()
return '添加成功!'
@app.route('/find_master/<int:dog_id>/')
def find_master(dog_id):
dog=Dogs.query.filter(Dogs.id==dog_id).first()
user_id=dog.master_id;
user=Users.query.filter(Users.id==user_id).first()
return user.name
if __name__=='__main__':
app.run(debug=True)
打开浏览器,先后输入
127.0.0.1:5000/adduser/
回车
127.0.0.1:5000/adddogs/
回车
再次执行上面数据库的命令,结果如下:
打开浏览器,输入
127.0.0.1:5000/find_master/2/
结果如下:
哦耶!