首页 > 解决方案 > SLQAlchemy 无法创建关系列

问题描述

提前致谢。我正在使用 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' 的外键

我的代码:

应用程序/__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)

应用程序/config.py

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

应用程序/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

标签: pythonflasksqlalchemy

解决方案


尝试通过修改:

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

经过

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

推荐阅读