我有以下应用程序.py:
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSON
import os
from psycopg2.extras import Json, DictCursor
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'secret_key'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or
'postgresql+psycopg2://postgres:password@localhost:5432/gkrs_test'
app = Flask(__name__)
app.config.from_object(Config)
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
class Teacher(db.Model):
__tablename__ = 'teacher'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
email = db.Column(db.String(120), unique=True)
password_hash = db.Column(db.String(128))
classes = db.relationship('Classes', back_populates='teacher', lazy='dynamic')
class Classes(db.Model):
__tablename__ = 'classes'
id = db.Column(db.Integer, primary_key=True)
teacher = db.Column(db.Integer, db.ForeignKey('teacher.id'))
name = db.Column(db.String(20))
day = db.Column(db.String(20))
time = db.Column(db.String(20))
students = db.Column(JSON)
class Viktorina(db.Model):
__tablename__ = 'viktorina'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
teacher = db.Column(db.Integer, db.ForeignKey('teacher.id'))
questions = db.Column(JSON)
当我转到python控制台并使用:
>>>from app import db
>>>from app import Teacher, Classes, Viktorina
>>>Teacher.query.get(1)
我得到以下异常:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:UsersVladPycharmProjectsgkrs-viktorinavenvlibsite-packagesflask_sqlalchemy__init__.py", line 512, in __get__
mapper = orm.class_mapper(type)
File "C:UsersVladPycharmProjectsgkrs-viktorinavenvlibsite-packagessqlalchemyormbase.py", line 451, in class_mapper
mapper = _inspect_mapped_class(class_, configure=configure)
File "C:UsersVladPycharmProjectsgkrs-viktorinavenvlibsite-packagessqlalchemyormbase.py", line 430, in _inspect_mapped_class
mapper._configure_all()
File "C:UsersVladPycharmProjectsgkrs-viktorinavenvlibsite-packagessqlalchemyormmapper.py", line 1352, in _configure_all
configure_mappers()
File "C:UsersVladPycharmProjectsgkrs-viktorinavenvlibsite-packagessqlalchemyormmapper.py", line 3295, in configure_mappers
raise e
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Teacher->teacher'. Original exception was: viewonly
我确信这些桌子不是空的,而且都至少有一行。我该如何解决此问题?我正在使用Postgresql。我在网上找到的东西都没有帮助,因为没有一个是只读的。
在行中
classes = db.relationship('Classes', back_populates='teacher', lazy='dynamic')
您告诉SQLAlchemy在"类"模型中创建字段"教师",但由于以下行,该字段已存在于类模型中:
teacher = db.Column(db.Integer, db.ForeignKey('teacher.id'))
也许你是想把课堂模型中的那个称为teacher_id?