ManyToMany with SQLalchemy in Fastapi



我有以下多对多关系模型:

dashboard_customer_association = Table(
"entry_customer",
Base.metadata,
Column("entry_id", ForeignKey("entry.id"), primary_key=True),
Column("customer_id", ForeignKey("customer.id"), primary_key=True),
)

class Customer(Base):
__tablename__ = "customer"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
name = Column(String(64), unique=True, index=True)

class Entry(Base):
__tablename__ = "entry"
id = Column(String(16), primary_key=True, index=True)
customer = relationship("Customer", secondary=dashboard_customer_association)

这是我的pydantic模式。

class Entry(BaseModel):
id: str
customer: List[str] = []
class Config:
orm_mode = True

我已经成功地插入了数据并创建了客户,但问题是,当我试图检索数据:

pydantic.error_wrappers.ValidationError: 2 validation errors for Entry
response -> customer -> 0
str type expected (type=type_error.str)
response -> customer -> 1
str type expected (type=type_error.str)

我知道Customer对象不是字符串,所以customer字段不能直接序列化为List[str],但我没有看到我该怎么做转换呢

我用以下函数返回数据:

def get_data(item_id):
instance = db.query(models.Entry).filter(models.Entry.id == item_id).first()
return instance

我试图设置instance.customer = [customer.name for customer in instance.customer],但是SQLalchemy阻止了这种情况。正确的做法是什么?

最好的方法是简单地将模式与返回的数据匹配,并同时拥有一个Customer对象。

然而,如果这不是一个选项,你可以使用一个验证器来改变内容,当它被填充-即只返回一个值从你的客户对象。

@validator('customer')
def customer_as_string(cls, v):
return v.name

最新更新