[英]Error in One to Many SQLAlchemy database with Flask
I am currently trying to insert items into my database. 我目前正在尝试将项目插入数据库。 I am using SQLlite and SQLAlchemy with Flask but there seems to be an issue. 我在Flask中使用SQLlite和SQLAlchemy,但似乎有问题。 Whenever I try to insert items manually from the cmd, I receive an error. 每当我尝试从cmd手动插入项目时,都会收到错误消息。
This session's transaction has been rolled back due to a previous exception during flush. 由于刷新期间先前存在异常,因此该会话的事务已回滚。
I have implemented an one to many relationship in my database but something seems to keep messing up. 我已经在数据库中实现了一对多关系,但是某些事情似乎一直在混乱。 Here is my Python code: 这是我的Python代码:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
main = Flask(__name__)
db = SQLAlchemy(main)
main.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://YYYYYYY:XXXXXXX@localhost/address'
main.config['SECRET_KEY'] = 'something-secret'
Bootstrap(main)
class Organisation(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), unique=True)
email = db.Column(db.String(40), unique=True)
number = db.Column(db.String(40), unique=True)
employees = db.relationship('Person', backref='employer', lazy='dynamic')
def __init__(self, title, email, number):
self.title = title
self.email = email
self.number = number
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60), unique=False)
email = db.Column(db.String(40), unique=True)
mobile = db.Column(db.String(40), unique=True)
employer_id = db.Column(db.Integer, db.ForeignKey('organisation.id'))
def __init__(self, name, email, mobile, employer_id):
self.name = name
self.email = email
self.mobile = mobile
self.employer_id = employer_id
@main.route('/', methods=['GET'])
def index():
result = Person.query.all()
org_result = Organisation.query.all()
return render_template("index.html", result=result, org_result=org_result)
@main.route('/additems', methods=['GET'])
def additems():
return render_template('add.html')
@main.route('/add', methods=['GET', 'POST'])
def add():
person = Person(request.form['name'], request.form['email'], request.form['mobile'])
db.session.add(person)
db.session.commit()
if __name__ == "__main__":
main.run(debug=True)
If I have to honest, I think that my issue is somewhere in the init functions. 如果我必须诚实地说,我认为我的问题出在init函数中。 I have tried changing them in several ways: 我尝试过几种更改方式:
1.Adding employees as self.employees = employees and trying directly to input an Organisation as: organisation_one=Organisation(title="XX",email="xx@mail.com",number="3838",employees=person_one)
but it fired back an error even before I could submit person_one
1.将员工添加为self.employees = employees,然后尝试直接输入组织为: organisation_one=Organisation(title="XX",email="xx@mail.com",number="3838",employees=person_one)
但它甚至在我可以提交person_one
之前就回传了错误
2.I have tried referencing the employer_id in the Person __init__ file and when I try to add the organisation id, I recive an error "can't adapt type". 2.我已经尝试引用了人__init__文件employer_id,当我尝试添加该组织的ID,我recive一个错误“无法适应型”。
What am I doing wrong with the one to many database model? 一对多数据库模型在做什么? Can someone help me out? 有人可以帮我吗?
Your database models require a __tablename__
attribute like this: This tells it what the actual table name is in the database. 您的数据库模型需要这样的__tablename__
属性:这可以告诉它数据库中实际的表名是什么。 Otherwise SQLAlchemy doesn't know how to write the SQL for you. 否则,SQLAlchemy不知道如何为您编写SQL。
class Organisation(db.Model):
__tablename__ = 'organisation'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), unique=True)
email = db.Column(db.String(40), unique=True)
number = db.Column(db.String(40), unique=True)
employees = db.relationship('Person', backref='employer', lazy='dynamic')
def __init__(self, title, email, number):
self.title = title
self.email = email
self.number = number
You must also reference this table name in the backref
for your Person model: 您还必须在您的Person模型的backref
引用此表名称:
db.ForeignKey('organisation.id')) # assuming "organisation" is the table name
Also, your /add
route is incomplete and will result in an error: 另外,您的/add
路由不完整,将导致错误:
@main.route('/add', methods=['GET', 'POST'])
def add():
person = Person(request.form['name'], request.form['email'], request.form['mobile'])
db.session.add(person)
db.session.commit()
# e.g. add some instruction here on what to do...
flash('Person %s <%s>added!' % (request.form['name'], request.form['email']))
return redirect(url_for('main.additems'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.