Flask数据库表找不到对方

时间:2017-07-11 17:31:47

标签: python sqlalchemy

我有基于SQLAlchemy的Flask数据库的以下代码:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

#Class for keeping track of users
class User(db.Model):
    user_id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(100), nullable = False)
    password = db.Column(db.String(100), nullable = False)
    messages = db.relationship('Message', backref = 'user', lazy = 'dynamic')
    chatrooms = db.relationship('ChatRoom', backref = 'user', lazy = 'dynamic')

    def __init__(self, name, pw):
        self.username = name
        self.password = pw

#Class for keeping track of chatrooms
class ChatRoom(db.Model):
    chat_id = db.Column(db.Integer, primary_key = True)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
    title= db.Column(db.String(100), nullable = False)
    high_msg_id = db.Column(db.Integer)
    messages = db.relationship('Message', backref ='chat', lazy='dynamic')

    def __init__(self, title, creator_id):
        self.title = title
        self.creator_id = creator_id
        self.high_msg_id = 0

    #Add a message to the chatroom
    def add(message):
        high_msg_id = high_msg_id + 1
        message.chat_thread_id = high_msg_id

#Class for keeping track of messages
class Message(db.Model):
    msg_id = db.Column(db.Integer, primary_key = True)
    text = db.Column(db.String(1000), nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
    chat_id = db.Column(db.Integer, db.ForeignKey('chat.chat_id'), nullable=False)
    chat_thread_id = db.Column(db.Integer)

    def __init__(self, txt, chat_id):
        self.text = txt
        self.chat_id = chat_id

但是每当我初始化它时我都会收到以下错误:与'messages.chat_id'列关联的外键无法找到用于生成目标列'chat_id'的外键的表'chat'。 我发现这非常奇怪,因为我没有为这个数据库中的任何其他关系得到这个错误,我不知道出了什么问题。

2 个答案:

答案 0 :(得分:1)

ChatRoom模型会生成一个名为chatroom而非chat的表格。因此,您需要将外键重命名为chatroom.chat_id或重命名生成的表,如下所示:

class ChatRoom(db.Model):
    __tablename__ = 'chat'
    # ...

答案 1 :(得分:0)

你把你的关系放在错误的班级上。

class User(db.Model):
    user_id = db.Column(db.Integer, primary_key = True)
    ...

class ChatRoom(db.Model):
    chat_id = db.Column(db.Integer, primary_key = True)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
    creator = db.relationship('User', backref='chatrooms_created')

class Message(db.Model):
    msg_id = db.Column(db.Integer, primary_key = True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
    chat_id = db.Column(db.Integer, db.ForeignKey('chat.chat_id'), nullable=False)

    user = db.relationship('User', backref='messages')
    chat_room = db.relationship('ChatRoom', backref='messages')

请参阅SQLAlchemy Documentation on relationships