flask Web开发5.7一对多关系的插入数据与查询问题

1.整体代码:

import os

from flask import Flask, render_template, session, redirect, url_for, flash

from flask_script import Manager

from flask_bootstrap import Bootstrap

from flask_moment import Moment

from flask_wtf import FlaskForm

from wtforms import StringField, SubmitField

from wtforms.validators import Required

from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)

app.config['SECRET_KEY'] = 'hard to guess string'

app.config['SQLALCHEMY_DATABASE_URI'] =\

'sqlite:///' + os.path.join(basedir, 'data.sqlite')

app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

manager = Manager(app)

bootstrap = Bootstrap(app)

moment = Moment(app)

db = SQLAlchemy(app)

class Role(db.Model):

__tablename__ = 'roles'

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.String(64), unique=True)

users = db.relationship('User', backref='role', lazy='dynamic')

def __repr__(self):

return '<Role %r>' % self.name

class User(db.Model):

__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(64), unique=True, index=True)

role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

def __repr__(self):

return '<User %r>' % self.username

class NameForm(FlaskForm):

name = StringField('What is your name?', validators=[Required()])

submit = SubmitField('Submit')

@app.errorhandler(404)

def page_not_found(e):

return render_template('404.html'), 404

@app.errorhandler(500)

def internal_server_error(e):

return render_template('500.html'), 500

@app.route('/', methods=['GET', 'POST'])

def index():

form = NameForm()

if form.validate_on_submit():

old_name = session.get('name')

if old_name is not None and old_name != form.name.data:

flash('Looks like you have changed your name!')

session['name'] = form.name.data

return redirect(url_for('index'))

return render_template('index.html', form=form, name=session.get('name'))

if __name__ == '__main__':

db.create_all()

manager.run()

2.数据表模型类一对多,Role和User

class Role(db.Model):

__tablename__ = 'roles'

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.String(64), unique=True)

users = db.relationship('User', backref='role', lazy='dynamic')

def __repr__(self):

return '<Role %r>' % self.name

class User(db.Model):

__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(64), unique=True, index=True)

role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

def __repr__(self):

return '<User %r>' % self.username

3.插入数据和查询数据

图片描述
图片描述

在插入数据时,主键可以不用传递,但是外键应该指定。我想知道这一块怎么理解,还是传一个role=user_role会自动识别出外键role_id??

回答:

SQLAlchemy会自动帮你解析user_role中的id,具体的SQLAlchemy使用方法,请移步官方文档

以上是 flask Web开发5.7一对多关系的插入数据与查询问题 的全部内容, 来源链接: utcz.com/a/163193.html

回到顶部