我刚开始使用SQLModel,我试图从我现有的库中实现一些基本代码,我有一个Address类
喜欢
@dataclass
class Address(DataClassJsonMixin):
addr1: str
city: str
province: str我只想在SQLModel中创建一个连接到DB的类。我只在这里添加了一个新的列ID。下面是错误,我不知道为什么它会要求一个config属性。
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"})发布于 2022-01-23 17:03:41
AdressMaster类的语义出现了错误。如果它是一个与您的DB相关的类。然后,您必须在第一个参数中指定从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在Try 1中:您试图向您的AddressDB类传递两个参数,其中一个是SQLModel。然而,SQLModel允许重写SQLAlchemy,并且只接受来自SQLAlchemy或Pydantic的参数模型。在初始化过程中,它会遍历参数中传递的参数,并尝试调用存在于pydantic和SQLAlchemy模型中的方法或属性SQLAlchemy。这是错误的来源,因为您传入参数DataClassJsonMixin,它没有Config方法或属性。这是你错误的根源。
如何解决这个问题。您只需不调用DataClassJsonMixin,在我看来,它似乎是编码/解码JSON数据的。然而,这是Pydantic (在SQLModel后面使用)的一个基本行为。
因此,如果使用上面所示的第一个方法(即从SQLModel继承的方法),只需将验证字段放在AddressDB中,并使该类仅从SQLModel继承
class AddressDB(SQLModel):
addr1: str
city: str
province: strhttps://stackoverflow.com/questions/70822063
复制相似问题