You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Beanie ODM插入文档时排除值为None的字段?

Beanie ODM插入时排除None值字段的解决方案

我在使用Beanie ODM插入文档时,希望不存储值为None的字段,但还没找到实现方法。相关路由代码如下:

@router.post('/signup')
async def signup(
        request: Request,
        user_create: SignupSchema
):
    hashed_password = get_password_hash(user_create.password)

    user_entity = UserEntity(**user_create.dict(), hashed_password=hashed_password)

    result = await user_entity.insert()
    if not result:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Error creating user",
            headers={"WWW-Authenticate": "Bearer"}
        )

    return JSONResponse(status_code=status.HTTP_201_CREATED,
                        content={"detail": "Account created successfully"})

我的UserEntity定义如下:

from typing import Optional
from beanie import Document
from pydantic import EmailStr

class UserEntity(Document):
        username: str
        email: EmailStr
        first_name: Optional[str]
        last_name: Optional[str]
        hashed_password: str

    class Settings:
        name = "users"

我想要实现类似user_create.dict(exclude_none=True)的效果,但针对Beanie ODM文档的.insert()方法,不希望数据库中存在无值的first_name/last_name字段。


方法一:创建实体前手动过滤None值

直接在构造UserEntity实例时,对user_create的字典数据使用exclude_none=True过滤掉值为None的字段,再传入参数:

@router.post('/signup')
async def signup(
        request: Request,
        user_create: SignupSchema
):
    hashed_password = get_password_hash(user_create.password)
    # 过滤掉所有值为None的字段
    filtered_user_data = user_create.dict(exclude_none=True)
    user_entity = UserEntity(**filtered_user_data, hashed_password=hashed_password)
    
    result = await user_entity.insert()
    if not result:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Error creating user",
            headers={"WWW-Authenticate": "Bearer"}
        )

    return JSONResponse(status_code=status.HTTP_201_CREATED,
                        content={"detail": "Account created successfully"})

方法二:通过文档类配置全局自动排除None值

如果希望该文档类的所有数据库操作都自动忽略None值字段,可以给UserEntity添加Pydantic的模型配置,设置exclude_none=True:

from typing import Optional
from beanie import Document
from pydantic import EmailStr

class UserEntity(Document):
    username: str
    email: EmailStr
    first_name: Optional[str]
    last_name: Optional[str]
    hashed_password: str

    # 配置全局排除None值字段
    model_config = {"exclude_none": True}

    class Settings:
        name = "users"

配置后,无论是插入还是更新操作,只要字段值为None,就不会被写入数据库,无需每次手动处理字典。

内容的提问来源于stack exchange,提问作者Risker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:31:10