如何解决sqlalchemy Invalid-Request-Error?

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

我想在用户和习惯之间创建关系,但我有一个问题:

 in get_property
    raise sa_exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper[Users(users)]' has no property 'users_habit'.  If this property was indicated from other mappers or configure events, ensure registry.configure() has been called.

代码:

from ..models import Base
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String


class Users(Base):
    
    __tablename__ = "users"
    
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    telegram_id: Mapped[int] = mapped_column(nullable=False)
    username: Mapped[String] = mapped_column(String(50), nullable=False)
    phone_number: Mapped[int]

...

from typing import List
from ..models import Base
from .users import Users
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, relationship, mapped_column


class Habits(Base):
    
    __tablename__ = "users_habits"
    
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    user: Mapped["Users"] = relationship(back_populates="users_habit")
    habit: Mapped[List[str]] = relationship(back_populates="users_habit")

我试图在网上搜索问题,但没有找到。

python database sqlalchemy relationship
1个回答
0
投票

错误消息通知您您的

Users
类没有名为
users_habit
的属性;检查您的
Users
类,情况确实如此 - 没有具有该名称的属性。

要解决此问题,您需要更新您的

Users
类,添加以下内容:

users_habit: Mapped["Habits"] = relationship(back_populates="user")

虽然上述内容将解决您遇到的具体错误,但您可能还需要解决其他一些问题:

  1. phone_number: Mapped[int]
    缺少列定义;根据您的具体实现,只需附加
    = mapped_column()
    就足够了
  2. 在您的
    Habits
    班级中,最后两行与
    =
    标志右侧相同;即:
    Habits.user
    Habits.habit
    都指同一件事:
    relationship(back_populates="users_habit")

    我怀疑您实际上想要将该关系分配给
    Habits
    的两个单独的属性,并且无论如何:您的PEP-484类型中只有一个可以是正确的(在本例中,第一个:
    Mapped["Users"]
    )。我不确定您想通过
    habit: Mapped[List[str]]
    实现什么目的,但这可能超出了这个问题线程的范围。
© www.soinside.com 2019 - 2024. All rights reserved.