SLQAlchemy无法创建关系列

时间:2019-12-06 05:49:00

标签: python flask sqlalchemy

先谢谢了。我正在开发Flask + SQLAlchemy中的应用程序。首先,我初始化了数据库flask db init

$ flask db init

  Creating directory /Users/xxxx/app/migrations ...  done
  Creating directory /Users/xxxx/app/migrations/versions ...  done
  Generating /Users/xxxx/app/migrations/script.py.mako ...  done
  Generating /Users/xxxx/app/migrations/env.py ...  done
  Generating /Users/xxxx/app/migrations/README ...  done
  Generating /Users/xxxx/app/migrations/alembic.ini ...  done
  Please edit configuration/connection/logging settings in '/Users/xxxx/app/migrations/alembic.ini'
  before proceeding.

然后我运行了flask db migrate。但是发生了一个错误,SQLAlchemy无法创建关系列。

  

与列“ post.user_id”关联的外键找不到表“ user”,通过该表生​​成用于将列“ id”作为目标的外键

我的代码:

app / __ init __。py

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object('app.config')

# migrate db
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app.db import (
    User, Post
)

def init_db(app):
    db.init_app(app)

app / config.py

SQLALCHEMY_DATABASE_URI = 'sqlite:///develop.db'
SECRET_KEY = 'secret key'
SQLALCHEMY_TRACK_MODIFICATIONS = False

app / db.py

from app import db

# Model
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    email = db.Column(db.String, unique=True)
    image = db.Column(db.String)
    uid = db.Column(db.String, unique=True)
    token = db.Column(db.String, unique=True)

    def __repr__(self):
        return '<User %r>' % self.uid

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    name = db.Column(db.String)
    content = db.Column(db.Text)

    def __repr__(self):
        return '<Post %r>' % self.content

2 个答案:

答案 0 :(得分:2)

尝试通过修改:

user_id = db.Column(db.Integer,db.ForeignKey('user.id'))

通过

user_id = db.Column(db.Integer,db.ForeignKey('users.id'))

答案 1 :(得分:1)

SQLAlchemy报告的分歧介于两者之间

class User(db.Model):
    __tablename__ = 'users'

user_id = db.Column(db.Integer,db.ForeignKey('user.id'))

选择“用户”或“用户”之一