【问题标题】:Flask + sqlalchemy + marshmallow - Error on relationship - One to ManyFlask + sqlalchemy + marshmallow - 关系错误 - 一对多
【发布时间】:2020-04-14 18:06:00
【问题描述】:

为什么这段代码会返回错误?

错误:初始化映射器 Mapper|Pessoa|pessoa 时,表达式 'Imovel' 未能找到名称(“名称 'Imovel' 未定义”)。

from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

db=SQLAlchemy()
ma=Marshmallow()

class Pessoa(db.Model):
    __tablename__ = 'pessoa'
    idLocal= db.Column(db.Integer, primary_key=True)
    Nome=db.Column(db.String(100), default=u'')
    imovelList = db.relationship("Imovel", back_populates="PessoaList")
    def get_id(self):
        return self.idLocal

class PessoaSchema(ma.ModelSchema):
    class Meta: model = Pessoa

class Imovel(db.Model):
    __tablename__ = 'imovel'
    idLocal= db.Column(db.Integer, primary_key=True)
    CodigoImovel=db.Column(db.String(30), default=u'')
    idPessoa = db.Column(db.Integer, db.ForeignKey('pessoa.idLocal'))
    PessoaList = db.relationship("Pessoa", back_populates="imovelList")
    def get_id(self):
        return self.idLocal

class ImovelSchema(ma.ModelSchema):
    class Meta: model = Imovel

【问题讨论】:

  • 也许可以尝试在课后移动PessoaSchema Imovel

标签: python flask sqlalchemy marshmallow


【解决方案1】:

您有“声明顺序”问题。当关系用字符串定义时,在构造映射器时立即初始化关系。但是,当您在“Imovel”上定义关系时,您尚未声明一个名为“Imovel”的映射器。 Imovel 映射器或类是在几行之后定义的。

因此,您可以将 Imovel 映射器移动到 Pessoa 映射器上方,但此时您将得到完全相同的错误,因为您也在建立从 Imovel 到 Pessoa 的关系。

因此,您希望使用将返回“Imovel”映射器的可调用函数来声明您的关系。这个函数通常只会在所有的 Mapper 都构建完成后才会被调用。因此,通过使用 lambda 函数,我们可以确保在您有机会设置 Imovel 类之前不会调用关系。

实际上,要修复此错误,请替换此行

imovelList = db.relationship("Imovel", back_populates="PessoaList")

有了这个

imovelList = db.relationship(lambda: Imovel, back_populates="PessoaList")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多