【问题标题】:Error when initializing mapper mapped SQLAlchemy初始化映射器映射的 SQLAlchemy 时出错
【发布时间】:2020-01-14 09:36:26
【问题描述】:

我有一个表,它在一对多关系中引用了其他 2 个表。

我已经尝试了很多东西,但我找不到我想做的类似示例。下面是发生错误时的代码和描述。

Conversas.py:

from .model import db
from sqlalchemy.dialects.postgresql import JSON

class Conversa(db.Model):
    __tablename__ = "conversas"
    id = db.Column('ConversaId',db.Integer, primary_key=True)
    fkEmpresa = db.Column('FkEmpresa', db.Integer, db.ForeignKey('empresas.empresaId'),nullable=False)
    fkTipoUsuario = db.Column('FKTipoUsuario', db.Integer,db.ForeignKey('tiposUsuarios.tipoUsuarioId'),nullable=False)
    # other fields

Empresas.py: 从 .model 导入数据库

class Empresa(db.Model):
    __tablename__ = "empresas"
    id = db.Column('empresaId',db.Integer, primary_key=True)
    #some fields
    empresaCaracteristicas = db.relationship('EmpresaCaracteristica', backref='empresas', lazy=True)
    conversas = db.relationship('Conversa', backref='empresas', lazy=True)

TipoUsuario.py:

class TipoUsuario(db.Model):
    __tablename__ = "tiposUsuarios"
    id = db.Column('tipoUsuarioId',db.Integer, primary_key=True)
    #some fields
    usuarios = db.relationship('Usuario', backref='tiposUsuarios', lazy=True)
    conversas = db.relationship('Conversa', backref='tiposUsuarios', lazy=True)

我尝试插入一些值,但出现此错误:

sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped failed to locate a name ("name '' is not defined"). If this is a class name, consider adding this relationship() to the <class 'banco_nestorgr.tabelas.tipoUsuarioModel.TipoUsuario'> class after both dependent classes have been defined

【问题讨论】:

    标签: python python-3.x flask flask-sqlalchemy


    【解决方案1】:

    TipoUsuario(db.Model) 类中的反向引用:不应该相同

    尝试重命名 backref

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      相关资源
      最近更新 更多