【问题标题】:How can I insert a None/Null value for a int column?如何为 int 列插入 None/Null 值?
【发布时间】: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 我的回答对你有用吗?

标签: python fastapi asyncpg


【解决方案1】:

我建议使用一些 ORM,例如 SQLalchemy ORM,或者甚至可以帮助我们删除带有 fastapi/sql 模型的样板(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语句中使用''

【讨论】:

    【解决方案2】:

    我的 DB 列类型是 int,我尝试将类变量设置为 "" 但是我收到一个错误,我正在传递一个字符串。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2018-04-13
      • 1970-01-01
      • 2021-08-25
      • 2011-09-22
      • 1970-01-01
      • 2013-09-05
      相关资源
      最近更新 更多