如何为 int 列插入 None/Null 值?

How can I insert a None/Null value for a int column?

我正在使用快速 API 并且我有一个可选输入。如果没有提供,我只是不想插入任何东西,这是我的 class:

class NetZeroAddGoalsRequest(BaseRequest):
    target: int
    description: str
    target_date: Optional[str] = "1/1/2050"
    update_frequency_month: Optional[int] = None

然后我将它更新到我的数据库中:

company, target, description, target_date, update_frequency_month = body.company.upper(), body.target, body.description, body.target_date, body.update_frequency_month

# insert into DB
res = await main_db_instance.fetch_rows(f"INSERT INTO company.transition_company (company_name, target_carbon, description, target_date, update_frequency_month)"
                                        f" VALUES ('{company}', '{target}', '{description}', '{target_date}', '{update_frequency_month}')"
                                        f" RETURNING *")

但我收到此错误:

invalid input syntax for type integer: "None"

我的 DB 列类型是 int,我尝试将 class 变量设置为“”,但随后出现错误,提示我正在传递字符串。

如何在 fast API 中有一个可选的 int?

编辑:如果有帮助,我正在使用 asyncpg - 我试图隔离它,它似乎与插入语句一起使用。如果我将其注释掉,那么我就不会收到错误消息。

我建议使用一些 ORM,比如 SQLalchemy ORM or even something that helps us remove boilerplate with fastapi/sql models (tortoise 在这里很棒!)用它们你可以做一些像

这样简单的事情
session.add(MyModel(**body.dict()))

但是如果你只是想让你的示例工作,请将 None 转换为 null,因为 db 不知道共 Nones

update_frequency_month = 'null' if update_frequency_month is None else update_frequency_month

并且不要在 sql 语句中使用 ''

my DB column type is int, and I've tried to set the class variable to "" but then I get an error that I'm passing a string.

None(Python类型,不是postgres/SQL类型)不是int,""不是int。如果您使用的是 asyncpg,它应该会自动将值从 None 转换为 null。我怀疑这是因为您使用格式化字符串将值直接插入 SQL。

尝试使用本机查询参数语法:

('''
    INSERT INTO company.transition_company (company_name, target_carbon..)
        VALUES (, ,..) 
 ''', company, target,..)