如何在SQLAlchemy中正确连接数据库。获取名称错误:未定义名称“User”

2024-04-27 05:02:41 发布

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

我正在和SQLAlchemy和flask建立一种多对多的关系。我想我已经正确地进行了所有导入,但由于某些原因,我得到了错误“NameError:name'User'is not defined”。你知道吗

我阅读了SQLAlchemy文档并尝试了它们的关联对象示例。下面是我自己的档案。例如,每个数据库模型都在自己的文件夹中应用型号.py(图片)在应用程序/图片文件夹中。你知道吗

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=关系(用户id,back\u populates=“喜欢”) 名称错误:未定义名称“User”


Tags: namefromimportselfiddbbaseapplication
1条回答
网友
1楼 · 发布于 2024-04-27 05:02:41

当您的模型插入无序时,应将模型名称括在“或”中。示例:

likers = relationship('User', back_populates="likes")
likes = relationship('Picture', back_populates="likers")

来自文档(https://docs.sqlalchemy.org/en/13/orm/relationship_api.html):

When using the Declarative extension, the Declarative initializer allows string arguments to be passed to relationship(). These string arguments are converted into callables that evaluate the string as Python code, using the Declarative class-registry as a namespace. This allows the lookup of related classes to be automatic via their string name, and removes the need for related classes to be imported into the local module space before the dependent classes have been declared. It is still required that the modules in which these related classes appear are imported anywhere in the application at some point before the related mappings are actually used, else a lookup error will be raised when the relationship() attempts to resolve the string reference to the related class.

相关问题 更多 >