【发布时间】:2022-01-22 22:59:13
【问题描述】:
我正在使用快速 API,并且我有一个可选输入。如果没有提供,我只是不想插入任何东西,这是我的课程:
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,我尝试将类变量设置为“”,但随后出现错误,提示我正在传递字符串。
我如何在快速 API 中有一个可选的 int?
编辑:如果有帮助,我正在使用 asyncpg - 我试图隔离它,它似乎与插入语句有关。如果我将其注释掉,则不会收到错误消息。
【问题讨论】:
-
您的数据库列可以接受空值吗,您是否可能不小心将其设置为不可为空?
-
@elano7 谢谢 - 我做了检查,int 列可以接受空值。
-
@Lostsoul 我的回答对你有用吗?