首页 > 编程问答 >sqlalchemy.exc.InvalidRequestError

sqlalchemy.exc.InvalidRequestError

时间:2024-07-22 14:59:12浏览次数:6  
标签:python sqlalchemy fastapi

我收到此错误,但我不明白如何解决它。当我使用 uvicorn 运行 FastApi 时出现此错误。要注意利用循环模型导入的错误,我使用了 TYPE_CHEKING

sqlalchemy.ext.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 
'Mapper[User(users)]'. Original exception was: When initializing mapper Mapper[User(users)], expression 'Times' failed to locate a name ('Times'). If 
this is a class name, consider adding this relationship() to the <class 'app.models.user_model.User'> class after bath dependent classes have been defined. 

我的模型定义如下:

class Times(Base):
    __tablename__ = 'times'

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
    booking_id: Mapped[int] = mapped_column(ForeignKey('bookings.id'))
    time: Mapped[str]

    user: Mapped['User'] = relationship('User', back_populates='times')
    booking: Mapped['Booking'] = relationship('Booking', back_populates='list_times')
class User(Base):
    __tablename__ = 'users'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(255))
    surname: Mapped[str] = mapped_column(String(255))
    profile_photo: Mapped[str] = mapped_column(String(255), default='default.jpg')
    role: Mapped[str] = mapped_column(String(255), default='user')
    email: Mapped[str] = mapped_column(String(255), unique=True)
    personal_link: Mapped[str] = mapped_column(String(255), unique=True)
    telegram_link: Mapped[str] = mapped_column(String(255), unique=True, default=None, nullable=True)
    hashed_password: Mapped[str]
    registered_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now(moscow_tz).replace(tzinfo=None))
    is_active: Mapped[bool] = mapped_column(default=True)
    description: Mapped[str | None] = mapped_column(String(500), default=None, nullable=True)
    enabled: Mapped[bool] = mapped_column(default=True)
    start_time: Mapped[time] = mapped_column(Time, default=time(7, 0))
    end_time: Mapped[time] = mapped_column(Time, default=time(20, 0))
    interval: Mapped[int] = mapped_column(default=30)
    

    bookings: Mapped[list['Booking']] = relationship('Booking', back_populates='user')
    times: Mapped[list['Times']] = relationship('Times', back_populates='user')
class Booking(Base):
    __tablename__ = 'bookings'

    id: Mapped[int] = mapped_column(primary_key=True)
    date_for_booking: Mapped[date] = mapped_column(Date, nullable=True)
    user_id: Mapped[int] = mapped_column(ForeignKey('users.id', ondelete='CASCADE'))
    times: Mapped[list[str]] = mapped_column(JSON, nullable=True)
    selected_times: Mapped[list[str]] = mapped_column(JSON, nullable=True, default=[])

    user: Mapped['User'] = relationship('User', back_populates='bookings')
    list_times: Mapped[list['Times']] = relationship('Times', back_populates='booking')

为了解决我遇到的问题,我尝试删除 Mapped ,以及关系中的 Model


The error message says that your User model is referencing the Times model before it has been defined. You need to define the Times model before the User model:

from sqlalchemy import ForeignKey, String, Integer, DateTime, Date, Time, JSON, Boolean
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime, time

from app.database import Base
from app.config import settings
from pytz import timezone

moscow_tz = timezone(settings.TIMEZONE)

class Times(Base):
    __tablename__ = 'times'

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
    booking_id: Mapped[int] = mapped_column(ForeignKey('bookings.id'))
    time: Mapped[str]

    user: Mapped["User"] = relationship('User', back_populates='times')
    booking: Mapped["Booking"] = relationship('Booking', back_populates='list_times')

class User(Base):
    __tablename__ = 'users'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(255))
    surname: Mapped[str] = mapped_column(String(255))
    # ... rest of your User model definition

    bookings: Mapped[list["Booking"]] = relationship('Booking', back_populates='user')
    times: Mapped[list["Times"]] = relationship('Times', back_populates='user')

class Booking(Base):
    __tablename__ = 'bookings'

    id: Mapped[int] = mapped_column(primary_key=True)
    date_for_booking: Mapped[date] = mapped_column(Date, nullable=True)
    # ... rest of your Booking model definition

    user: Mapped["User"] = relationship('User', back_populates='bookings')
    list_times: Mapped[list["Times"]] = relationship('Times', back_populates='booking')

This ensures that Python knows what Times refers to when it's used in the User model.

Additionally:

  • Make sure you are importing all necessary modules correctly at the beginning of your models file.
  • You might need to clear your SQLAlchemy metadata and recreate your tables if you have already run migrations with the incorrect model order.

By defining Times before User , SQLAlchemy should be able to correctly establish the relationship between them and resolve the error.

标签:python,sqlalchemy,fastapi
From: 78775039

相关文章

  • Python 实现Excel和TXT文本格式之间的相互转换
    Excel是一种具有强大的数据处理和图表制作功能的电子表格文件,而TXT则是一种简单通用、易于编辑的纯文本文件。将Excel转换为TXT可以帮助我们将复杂的数据表格以文本的形式保存,方便其他程序读取和处理。而将TXT转换为Excel则可以将文本文件中的数据导入到Excel中进行进一步的分析和......
  • Python (Django) 数据操作
    “如何将Excel考勤数据转换为特定的数据库插入格式?”**我Excel中的数据如下所示:**这是数据格式I**需要将其转换为适合数据库插入的格式,如下所示:**我想要的数据将Excel考勤数据转换为特定数据库插入格式的Python......
  • 在 python 中表示矩阵等价类的好方法是什么?
    我正在尝试编写一个程序来对井字棋进行强化学习。我希望引擎认识到,如果您反射棋盘或旋转它,您会得到完全相同的游戏,因此这些棋盘应该被视为彼此相同。目前我有一本字典,代表我当前对每个棋盘的估计估值游戏中的棋盘,每次游戏结束时,该游戏期间发生的所有棋盘位置的估值都会根据它......
  • MIT自学---python---6.100A_lecture2
    MIT自学---python---6.100A_lecture2前言一、设置python编译器地址二、将运行python文件的命令简化三、终端尝试执行简单python命令四、今日学到的python命令个人总结前言  这两天去听讲座,没什么时间按照计划自学MIT,今天赶紧补上。今天主要任务是搭建vscodepython......
  • python pip 需要构建工具,而它已经安装
    我看到这个问题已经被发布了很多次,人们设法解决了这个问题,但我没有!!操作系统版本:Windows1021H1Build19043.1288Python版本:Python3.9.7(tags/v3.9.7:1016ef3,Aug302021,20:19:38)[MSCv.192964bit(AMD64)]onwin32Pip、wheel和setuptool都可以日期:......
  • 无法在浏览器中访问Python 127.0.0.1:8000上的本地主机
    fromdjango.contribimportadminfromdjango.urlsimportpath,includeurlpatterns=[path('admin/',admin.site.urls),path('products/'),include('products.urls')#thisline]嗨,任何人。很抱歉问这样的问题,但这是我第一次尝试python。......
  • 在 VSCode 中通过 Python 使用 YouTube API 时如何启用 Intellisense
    我想在使用GoogleYouTubeAPI和Python时在VSCode中获得IntelliSense。但我不知道详细步骤。fromgoogleapiclient.discoveryimportbuildapi_key="****"youtube=build("youtube","v3",developerKey=api_key)request=youtube.channels().list(part......
  • 当 python 脚本通过 jenkins + Github 在 Windows 本地计算机上运行时,chrome 浏览器不
    我的Python代码是(windowsMachine)fromseleniumimportwebdriverprint("newLine")print("2Line")print("3Line")holdChrome=webdriver.ChromeOptions()holdChrome.add_experimental_option("detach",True)#Restricta......
  • python_基础_数据类型
    基础数据类型不需要声明,只有被赋值后才会创建变量。变量本身没有类型,“类型”指的是所存值的类型。类型判断type(x)和isinstance(x,int)前者不会认为子类是一种他的父类类型后者会认为子类是父类类型>>>classA:...pass...>>>classB(A):...pass......
  • IPython 使用技巧
    IPython是一个强大的交互式Pythonshell,提供了许多方便的功能,使Python编程更加高效和愉快。本文将介绍一些IPython的实用技巧,帮助开发者充分利用其功能,提高编程效率。1.基本操作和快捷键1.1启动IPython可以通过在终端输入以下命令来启动IPython:ipython启动后,你......