Flask+sqlalchemy+棉花糖一对多关系错误

2024-04-20 01:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么此代码返回错误?你知道吗

Error: When initializing mapper Mapper|Pessoa|pessoa, expression 'Imovel' failed to locate a name ("name 'Imovel' is not defined").

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

Tags: namefromimportselfflaskdbsqlalchemycolumn
1条回答
网友
1楼 · 发布于 2024-04-20 01:52:54

你有一个“申报顺序”问题。当用字符串定义关系时,在构造映射器时,关系会立即初始化。但是,当您在“Imovel”上定义关系时,还需要声明一个名为“Imovel”的映射器。Imovel映射器或类在此之后定义了几行。你知道吗

因此,您可以将Imovel映射器移到Pessoa映射器的上方,除非这样您会得到与从Imovel到Pessoa构建关系完全相同的错误。你知道吗

因此,您希望使用一个可调用函数来声明您的关系,该函数将返回“Imovel”映射器。此函数通常仅在构造所有映射器之后调用。因此,通过使用lambda函数,我们可以确保在您有机会设置imevel类之前不会调用关系。你知道吗

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

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

用这个

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

相关问题 更多 >