0

我是 fastapi 和 SQLModel 的新手,我试图从我现有的库中实现一些基本代码,我有一个地址类

喜欢

@dataclass
class Address(DataClassJsonMixin):
    addr1: str
    city: str
    province: str

我只是想在 SQLModel 中创建一个连接到 DB 的类。我在这里只添加了一个新的列 ID。我遇到错误,我不确定为什么它要求配置属性。

class AddressMaster(SQLModel, Address):
    id: int = Field(default=None, primary_key=True)


AttributeError: type object 'Address' has no attribute '__config__'

它失败了config = getattr(base, "__config__"),有一些我无法理解的信息。

# Only one of the base classes (or the current one) should be a table model
# this allows FastAPI cloning a SQLModel for the response_model without
# trying to create a new SQLAlchemy, for a new table, with the same name, that
# triggers an error

尝试1:

from sqlmodel import SQLModel, Field
from ...core import Address
from dataclasses import dataclass


@dataclass
class AddressDB(Address, SQLModel):
    pass

# END AddressDB

class AddressMaster(AddressDB, table=True):
    """
    Address Master Table
    """
    id: int = Field(default=None, primary_key=True)

# END AddressMaster

对象创建

objAd = AddressMaster.from_dict({"addr1": "Kashmir", "city": "Srinagar", "province": "Kashmir"})
4

1 回答 1

0

AdressMaster您的类的语义存在错误。如果它是与您的数据库相关的类。然后您必须在第一个参数中指定继承自 SQL 模型的类或SQLmodel直接从(在这种情况下,您应该重写该类中模型的每个属性)的类。并且有必要将参数传递给它table=True

class AddressMaster(Address, table=True):
    id: int = Field(default=None, primary_key=True)
    # Here the attributes will be inherited from your Adress class 
    # (provided that this one in its parentage is an inheritance link with a modelSQL)

或者

class AddressMaster(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    addr1: str
    city: str
    province: str
    # Here, the class is independent from the other pydantic 
    # validation models since it inherits directly from SQLModel

在尝试 1 中:您试图将两个参数传递给您的AddressDB类,其中一个是SQLModel. 但是,SQLModel允许覆盖 SQLAlchemy,并且只接受来自 SQLAlchemy 或 Pydantic 的模型作为参数。在初始化过程中,它会遍历参数中传递的参数,并尝试调用Configpydantic 和 SQLAlchemy 模型中存在的方法或属性。这是您的错误的根源,因为您传入的参数 aDataClassJsonMixin没有Config方法或属性。这是您错误的根源。

如何解决它。你只需要不调用DataClassJsonMixin在我看来编码/解码 JSON 数据的方法。然而,这是 Pydantic(在 SQLModel 后面使用)的基本行为。

因此,如果您使用上面显示的第一种方法(即从 SQLModel 继承),您只需将验证字段放入AddressDB其中并使此类仅继承自SQLModel

class AddressDB(SQLModel):
    addr1: str
    city: str
    province: str
于 2022-01-23T17:03:41.090 回答