我对Flask-SQLAlchemy有一个奇怪的问题。当我尝试通过Flask应用程序更新模型时,我收到以下错误,但在通过终端执行时工作正常。我正在通过邮递员提出请求(http://localhost:5000/changecontrols/2)。记录在那里,就像我说终端的工作正常。
Error: 'Foreign key associated with column 'ChangeControls.client_id' could not find table 'Clients' with which to generate a foreign key to target column ‘id’
我的结构如下:
我正在执行一个put请求,其中application / json类型是: { “名称”:“数据补丁” }
App.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
from webapi import *
if __name__ == '__main__':
app.run()
WebApi.py
from app import db
@app.route("/changecontrols/<string:id>", methods=["PUT"])
def update_change_control(id):
data = request.get_json()
change_control = ChangeControl.query.get(id)
if change_control is None:
return jsonify({"result": "change control was not found"}), 404
change_control.name = data["name"]
---> **db.session.commit() **<- This is where the error occurs****
return jsonify(change_control.serialize()), 200
ChangeControl中
from app import db
class ChangeControl(db.Model):
__tablename__ = 'ChangeControls'
id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True)
number = db.Column(db.String(20), nullable=False)
name = db.Column(db.String(200), nullable=False)
type = db.Column(db.String(50), nullable=True)
client_id = db.Column(db.Integer, db.ForeignKey('Clients.id'))
def load_from_json(self, data):
self.name = data.get("name",self.name)
self.number = data.get("number",self.number)
self.type = data.get("type", self.type)
客户端
from app import db
class Client(db.Model):
__tablename__ = 'Clients'
id = db.Column(db.Integer, primary_key=True, autoincrement=True )
name = db.Column(db.String(100), nullable=False)
startdate = db.Column(db.DateTime , default=datetime.datetime.utcnow())
inactivedate = db.Column(db.Date, nullable=True)
changecontrols = db.relationship('ChangeControl', backref='client', lazy='dynamic')
def load_from_json(self, data):
self.id = data["id"]
self.name = data["name"]
self.number = data["number"]
感谢您查看我的帖子:)
答案 0 :(得分:0)
这是因为您没有在app.py
中导入模型。尝试在您的app.py
文件中添加以下内容:
from models.ChangeControl import ChangeControl
from models.Client import Client
from webapi import *
这样,您无需将所有模型都放在一个软件包中。