在SQL AlChemy/FastApi中,如何在数据库中插入一个BaseModel类的列表?

chhkpiq4  于 2022-09-18  发布在  Java
关注(0)|答案(1)|浏览(214)

我希望在名为“Computers”的表中为其某些列动态插入一些行(这些列事先是未知的,这就是我使用术语“动态”的原因)。

为此,我创建了一个名为“ColumnIn”的BaseModel类,它有两个参数:“name”(描述列的名称)和“Value”(描述我们希望影响该列的值):

from fastapi import FastAPI
from sqlalchemy import MetaData, Table, insert, Column, Integer, String, create_engine
from pydantic import BaseModel
from typing import List, Union, Set

engine = create_engine("postgresql://postgres:f7Af&JhyuqdD@localhost/collector", pool_pre_ping=True, echo=True)
metadata_obj = MetaData()
computers = Table("computers", metadata_obj, autoload_with=engine)

class ColumnIn(BaseModel):
    name: Union[str, None] = None
    value : Union[str, None] = None

class ItemIn(BaseModel):
    db_name: Union[str, None] = None
    table_name: Union[str, None] = None
    other: List[ColumnIn]

app = FastAPI()

@app.post("/computers/")
async def create_computer(item: ItemIn):
    try:
        with engine.connect() as conn:
            result = conn.execute(
                insert(computers),
                [ val for val in item.other])
            conn.commit()
            return item
    except Exception as e:
        print(e)
        return item

当我执行POST时,FastAPI端没有错误,但数据库端出现错误(SQL AlChemy):

应为Set/Values列表达式或字符串键,GET(‘name’,‘thename’)。

你明白这个错误吗?

谢谢

[编辑]:

准确地说,用来代替:

[ val for val in item.other]

这显然是行不通的,我需要这样的东西:

{"name": "thename", "ip": "theip"}

其中,我可以动态指定此DICT的所有值(因为根据大小写的不同,列的名称和值将会改变)

gab6jxml

gab6jxml1#

好的,我只是在这里放了一个对我有效的解决方案

dico = {}
for it in item.other:
    dico[it.name] = it.value

try:
    with engine.connect() as conn:
        result = conn.execute(

            insert(computers),
            [   
                dico
            ]
        )
        conn.commit()
        return item

相关问题