gpt4 book ai didi

python - sqlalchemy 外键找不到表

转载 作者:行者123 更新时间:2023-12-05 02:11:58 26 4
gpt4 key购买 nike

我正在使用 sqlalchemy 创建一个数据库,它由三个类组成,User、Meeting、MeetingRoom我想在 Meeting 中为 session 室创建一个外键,但由于某种原因它给出了以下错误

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'meeting.mrid' could not find table 'meetingroom' with which to generate a foreign key to target column 'mrid'

Error screenshot

当我们反其道而行之时(在 session 室中添加一个 session 外键)它起作用了,我不确定问题出在哪里这是代码:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# ==================================
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
# ====================DATABASE
# =============USER
class User (db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(30))
Email = db.Column(db.String(30))
Pass = db.Column(db.String(30))
Phone = db.Column(db.String(12))
Department = db.Column(db.String(30))
Major = db.Column(db.String(30))
meeting = db.relationship('Meeting', backref='creator')
meetingroom = db.relationship('MeetingRoom', backref='reserver')

def __init__(self, name, Email, Pass, Phone, Department, Major):
self.name = name
self.Email = Email
self.Pass = Pass
self.Phone = Phone
self.Department = Department
self.Major = Major


# ================== MEETING ROOM
class MeetingRoom (db.Model):
mrid = db.Column(db.Integer,primary_key=True)
reserver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
meetingm = db.relationship('Meeting', backref='mrid')
#mid = db.Column(db.Integer, db.ForeignKey('meeting.Mid'))

def __init__(self, mrid, reserver_id):
self.mrid = mrid
self.reserver_id = reserver_id


# =======================MEETING
class Meeting (db.Model):
Mid = db.Column(db.Integer,primary_key=True)
Mname = db.Column(db.String(100))
Des = db.Column(db.String(100))
Date = db.Column(db.String(20))
creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#meetingroomm = db.relationship('MeetingRoom', backref='mroom')
mrid = db.Column(db.Integer, db.ForeignKey('meetingroom.mrid'))
#roomno_id = db.Column(db.Integer, db.ForeignKey('meetingroom.mrid')

def __init__(self, Mname, Des, Date, creator_id, mrid):
self.Mname = Mname
self.Des = Des
self.Date = Date
self.creator_id = creator_id
self.mrid = mrid

最佳答案

SqlAlchemy 正在使用自己的表名方案创建表并使用 meeting_room。因此,您在 relationship 中引用此名称,或者您可以通过在模型类上设置 __tablename__ 属性来覆盖。像这样:

class MeetingRoom (db.Model):
__tablename__ = 'meetingroom'

关于python - sqlalchemy 外键找不到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com