SQL Alchemy 问题:sqlalchemy.exc.InvalidRequestError

问题描述 投票:0回答:1

我遇到的错误就是这个(在尝试测试用户对象的 GET 之后,同时创建 CRUD 端点):

sqlalchemy.exc.InvalidRequestError:初始化映射器Mapper[User(users)]时,表达式“Favorite”无法找到名称(“Favorite”)。如果这是一个类名,请考虑在定义两个依赖类后将此关系()添加到 类。

这是我的代码:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    first_name = Column(String, index=True)
    last_name = Column(String, index=True)
    email = Column(String, index=True)
    password = Column(String, index=True)
    
    
    # ! here is the problem, but removing it will strip the
    # ! the possibility of navigating the tables.
    favorites = relationship('Favorite')

对于最爱的人:

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from app.schemas.user import User
from app.schemas.article import Article
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Favorite(Base):
    __tablename__ = "favorites"

    id = Column(Integer, primary_key=True, index=True)
    id_user = Column(Integer, ForeignKey(User.__table__.c.id))
    id_article = Column(Integer, ForeignKey(Article.__table__.c.id))
    
    #user = relationship('User')    
    #article = relationship('Article', back_populates='favorites')

这是我用来创建表的代码: 从 app.config.creds 导入 DATABASE_URL

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from app.schemas.favorite import Base as FavoriteBase

from app.schemas.user import Base as UserBase
from app.schemas.article import Base as ArticleBase

engine = create_engine(DATABASE_URL)

ArticleBase.metadata.create_all(bind=engine)
print('Article table created!')
FavoriteBase.metadata.create_all(bind=engine)
print('Favorite table created!')
UserBase.metadata.create_all(bind=engine)
print('User table created!')  


SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

print('Database setup complete!')

我该如何解决这个问题?并正在删除

   favorites = relationship('Favorite)
“有害”?

我尝试将所有内容合并到一个文件中,删除一些关系,唯一有效的方法(但这不是我从一对多关系中需要的)是删除这一行:

   favorites = relationship('Favorite)

python sql sqlalchemy foreign-keys fastapi
1个回答
0
投票

SQLAlchemy
正在定义
Favorite
模型的同一元数据对象中查找
User
模型。但是您将它链接到另一个元数据对象(另一个
Base
对象)。

您必须为所有具有关系的模型使用一个

Base
对象。

在单独的模块中创建

Base
并将其导入到所有带有模型的模块中。

© www.soinside.com 2019 - 2024. All rights reserved.