SQLAlchemy-自引用表出错

时间:2018-12-03 23:38:27

标签: python sql sqlalchemy flask-sqlalchemy

我正在尝试构建一个用户可以在其中回复其他帖子的系统,但是在尝试运行该程序时出现错误:

void Weapon::DeleteByIndex(std::vector<Bullet>::iterator &itr)
{
    destroySprite((*itr).GetSprite());
    bullets.erase(itr);
}

这是我的代码:

sqlalchemy.exc.InvalidRequestError:
    One or more mappers failed to initialize - can't proceed with initialization of other mappers.
    Triggering mapper: 'Mapper|Post|post'.
    Original exception was: 'Table' object has no attribute 'id'

1 个答案:

答案 0 :(得分:0)

您的代码对我有用。您还没有其他东西吗?您如何执行数据库创建?

这是我运行此文件的方式。我不得不添加自己的用户和组,并删除了pidgen.get(),因为不清楚它们的来源。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import pytz

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    def __repr__(self):
        return '<User %r>' % self.username

class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    def __repr__(self):
        return '<Group %r>' % self.name

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500))
    body = db.Column(db.String(10000))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    children = db.relationship('Post', backref='parent', lazy='dynamic')
    group_id = db.Column(db.Integer, db.ForeignKey('group.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('post.id'))
    def __repr__(self):
        return '<Post {}>'.format(self.body)

db.create_all()

运行方式:

python testapp.py

给我这个

sqlite> .schema post
CREATE TABLE post (
    id INTEGER NOT NULL, 
    title VARCHAR(500), 
    body VARCHAR(10000), 
    timestamp DATETIME, 
    user_id INTEGER, 
    group_id INTEGER, 
    parent_id INTEGER, 
    PRIMARY KEY (id), 
    FOREIGN KEY(user_id) REFERENCES user (id), 
    FOREIGN KEY(group_id) REFERENCES "group" (id), 
    FOREIGN KEY(parent_id) REFERENCES post (id)
);
CREATE INDEX ix_post_timestamp ON post (timestamp);