How to use a reserved keyword in pydantic model

Matheus

I need to create a schema but it has a column called global, and when I try to write this, I got an error.

class User(BaseModel):

    id:int
    global:bool

I try to use another name, but gives another error when try to save in db.

mx0

It looks like you are using the pydantic module. You can't use the name global because it's a reserved keyword so you need to use this trick to convert it.

class User(BaseModel):
    id: int
    global_: bool

    class Config:
        fields = {
            'global_': 'global'
        }

or

class User(BaseModel):
    id: int
    global_: bool = Field(..., alias='global')

To create a class you have to use a dictionary (because User(id=1, global=False) also throws an error:

user = User(**{'id': 1, 'global': False})

To get data in correct schema use by_alias:

user.dict(by_alias=True)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to use reserved keyword as the name of variable in python?

How to use reserved keyword 'year' in dynamodb query

Use reserved keyword a enum case

How do i use nested model with none value in pydantic

How to parse ObjectId in a pydantic model?

how to model nested object with pydantic

How to model an empty dictionary in pydantic

TS: Escaping reserved keyword and use as variable name

Use @validator in pydantic model for date comparison

How to access to a NSdictionary element with reserved keyword?

how to check if a dynamodb attribute is a reserved keyword (in Python)

How do add an assembled field to a Pydantic model

How to define a Pydantic model nested under a class

How does `mypy` know the signature of the pydantic model?

thrift js:node - Cannot use reserved language keyword: "not"

Why is "use strict" a plain string and not a JavaScript reserved keyword?

How to use different Pydantic Models in a view

Is it possible to use inheritance on the `schema_extra` config setting of a Pydantic model?

What is the correct type hint to use when exporting a pydantic model as a dict?

How to convert JSON payload with reserved keyword as name to record in Ballerina

How to avoid SqlException if SQL query contains reserved keyword?

In spark SQL/Hive QL, How to select a column that is a reserved keyword

How to pass a reserved keyword as a prop in reason-react

How to escape reserved word (keyword) in InterSystems Caché SQL?

How to access a valid OCaml identifier from Reason that is a reserved keyword in Reason

Vue 3 - How to rename reserved keyword exposed via toRefs()?

How to declare and init nested enum with reserved keyword as type name in Swift?

How to Check the given string is a reserved keyword in sql server

How to rename H2 SQL column with reserved keyword