【问题标题】:sqlalchemy [ORM] - add/inset to multiple tablessqlalchemy [ORM] - 添加/插入到多个表
【发布时间】:2021-06-25 23:37:55
【问题描述】:

我已经创建了架构和 2 个表模型以及它们之间的关系。



class SubscriberBase(BaseModel):
    subscriber_no: int
    is_active: bool = False

class SubscriberCreate(BaseModel):
    pass


class Subscriber(SubscriberBase):
    owner: int

    class Config:
        orm_mode = True

class CustomerCreate(BaseModel):
    customer_no: int
    subscriber: Optional[List[SubscriberBase]] = None

class Customer(CustomerCreate):
    id: int
    class Config:
        orm_mode = True

型号:


class CustomerModel(Base):
    __tablename__ = 'customer'
    id = Column(Integer, primary_key=True, index=True)
    customer_no= Column(Integer,index=True)
    subscriber= relationship("SubscriberModel", back_populates="owner")


class SubscriberModel(Base):
    __tablename__ = 'subscriber'
    id = Column(Integer, ForeignKey("customer.id"))
    subscriber_no= Column(Integer, primary_key=True, index=True)
    owner = relationship("CustomerModel", back_populates="subscriber")

对于以下字典输入:

test = {'customer_no': 2, 'subscriber': [{'subscriber_no': 2, 'is_active': False}, {'subscriber_no': 1, 'is_active': False}]}

我希望它会在客户表中插入一行, 和订阅者表中的 2 行。

试过了:

    db_customer = models.CustomerModel(**test)
    db.add(db_customer)
    db.commit()
    db.refresh(db_customer)

出现错误:

  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1675, in emit_backref_from_collection_append_event
    child_state, child_dict = instance_state(child), instance_dict(child)
AttributeError: 'dict' object has no attribute '_sa_instance_state'

sqlalchemy orm 如何插入多个表? 是否可以在一次插入中同时插入客户表和订户表?


@van

用更多信息更新帖子: 我正在使用“客户”(我上面提到的“测试”字典)的 fastapi is 实际上是 pydantic ,我确实尝试了以下方法:


@customer_router.post("/customer/")
def overloaded_create_customer(customer: CustomerCreate, db: Session = Depends(get_db)):
    
    db_customer = CustomerModel(**dict(customer))
    db.add(db_customer)
    db.commit()
    db.refresh(db_customer)

它返回类似的错误:


  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1675, in emit_backref_from_collection_append_event
    child_state, child_dict = instance_state(child), instance_dict(child)
AttributeError: 'SubscriberBase' object has no attribute '_sa_instance_state'

【问题讨论】:

    标签: python sqlalchemy orm


    【解决方案1】:

    创建一个 ORM 模型实例(就像您尝试使用 CustomerModel 一样)不是这样做的方法。相反,假设这些是 pydantic 模式,您应该尝试以下方式:

    # create pydantic model from the dictionary
    cust_schema = schemas.Customer.parse_obj(test)
    
    # convert to ORM model
    db_customer = models.CustomerModel(**dict(cust_schema))
    
    # ... (rest of your code)
    

    【讨论】:

    • 谢谢,我认为我所做的,我正在使用 fastapi,我已经准备好客户 pydantic 模型 - 我用更多信息更新帖子。
    • 仍在努力寻找解决方案。
    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2018-04-17
    • 2021-07-06
    • 2021-06-26
    相关资源
    最近更新 更多