【问题标题】:ManyToMany with SQLalchemy in Fastapi在 Fastapi 中使用 SQLalchemy 进行多对多
【发布时间】:2023-03-03 23:33:01
【问题描述】:

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

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 对象。如果这不是一个选项,您还可以使用验证器返回单个值:pydantic-docs.helpmanual.io/usage/validators
  • 验证器似乎在这里工作正常,这就是我所需要的。谢谢。

标签: python sqlalchemy many-to-many fastapi pydantic


【解决方案1】:

最好的方法是简单地将架构与返回的数据相匹配,并拥有一个 Customer 对象。

但是,如果这不是一个选项,您可以在填充时 use a validator to change the content - 即只从您的 Customer 对象返回一个值。

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

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2021-09-24
    • 2021-12-03
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多