Fastapi 中使用 SQLalchemy 的 ManyToMany

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],但我看不到 我应该如何进行转换。

我return具有以下功能的数据:

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 阻止了这种情况。正确的做法是什么?

最好的方法是简单地将架构与 returned 数据相匹配,并且还有一个客户对象。

但是,如果这不是一个选项,您可以 use a validator to change the content 在它被填充时 - 即 return 来自您的客户对象的单个值。

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