我正在创建与 SQLAlchemy 和 Flask 的多对多关系。我想我已经正确地进行了所有导入,但由于某种原因,我收到错误“NameError: name 'User' is not defined”。
我阅读了 SQLAlchemy 文档并尝试了他们的关联对象示例。下面是我自己的文件。每个 db 模型都在它自己的文件夹中的 application 下,例如 application/pictures 文件夹中的 models.py (Picture)。
from sqlalchemy.orm import relationship
from application import db
from application.Base import Base
class Picture(Base):
__tablename__ = "picture"
#some code
account_id = db.Column(db.Integer, db.ForeignKey("account.id"), nullable=False)
likers = relationship("Likes", back_populates="likes")
def __init__(self, name):
self.path = name
from sqlalchemy.orm import relationship
from application import db
from application import Base
class User(Base):
__tablename__ = "account"
#some code
likes = relationship("Likes", back_populates="likers")
def __init__(self, name, username, password):
self.name = name
self.username = username
self.password = password
#code associated to login
from sqlalchemy.orm import relationship, backref
from application import db
from application import Base
class Likes(Base):
__tablename__ = "like"
#some code
account_id = db.Column(db.Integer, db.ForeignKey('account.id'),
nullable=False)
picture_id = db.Column(db.Integer, db.ForeignKey('picture.id'),
nullable=False)
likers = relationship(User, back_populates="likes")
likes = relationship(Picture, back_populates="likers")
def __init__(self, account_id, picture_id):
self.account_id = account_id
self.picture_id = picture_id
#I have also imported the like db to __init__.py file before db.create_all()
from application.likes import models
我排除了正确连接的数据库,但我收到一条错误消息
likers = relationship(User.id, back_populates="likes") NameError: name 'User' 未定义
当您的模型插入无序时,您应该将模型名称括在 ` 或 " 中。例如:
likers = relationship('User', back_populates="likes")
likes = relationship('Picture', back_populates="likers")
来自文档(https://docs.sqlalchemy.org/en/13/orm/relationship_api.html):
使用声明式扩展时,声明式初始值设定项允许将字符串参数传递给 relationship()。这些字符串参数被转换为可调用对象,使用声明性类注册表作为命名空间,将字符串计算为 Python 代码。这允许通过它们的字符串名称自动查找相关类,并且不需要在声明依赖类之前将相关类导入本地模块空间。仍然需要在实际使用相关映射之前的某个时刻将出现这些相关类的模块导入应用程序中的任何位置,否则当 relationship() 尝试解析对相关类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句