pythonmongodbfastapipydantictornado-motor

exclude None fields from beanie ODM document


Im trying to insert a document from Beanie ODM without the fields with None value, but I can't find the way to do it

@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"})

Something like user_create.dict(exclude_none=True) but with the BeanieODM document .insert(), my UserEntity document is something like this:

from typing import Optional
from beanie import Document

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

    class Settings:
        name = "users"

I don't want the fields first_name/last_name in the database if they don't have a value. There should be some way of making Beanie ODM document's fields optional right?


Solution

  • Update: this is now supported using the keep_nulls flag in Settings.

    https://beanie-odm.dev/tutorial/defining-a-document/#keep-nulls