Flask-SqlAlchemy - 与列''关联的外键无法找到表

问题描述 投票:2回答:1

我对Flask-SQLAlchemy有一个奇怪的问题。当我尝试通过Flask应用程序更新模型时,我收到以下错误,但是当通过终端执行时工作正常。我正在通过邮递员做一个put请求(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’

我的结构看起来像这样:

  • changemanger 楷模 切换控制 客户
  • app.朋友
  • Web API.朋友

我正在执行一个put请求,其中application / json类型为:{“name”:“Data Patch”}

app.朋友

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()

Web API.朋友

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

切换控制

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"]

这个相同的代码在终端上工作没有错误?!?! enter image description here

谢谢你看我的帖子:)

flask flask-sqlalchemy
1个回答
0
投票

那是因为你没有在你的app.py中导入你的模型。尝试在app.py文件中包含以下内容:

from models.ChangeControl import ChangeControl
from models.Client import Client
from webapi import *

这样您就不需要将所有模型都放在一个包中。

© www.soinside.com 2019 - 2024. All rights reserved.