0

I run these codes by defining two classes, Blackboard and Table, based on BaseModel. The I defined another class which takes two attributes: bloackboard, defined to be a Blackboard; tables, defined to be a list of Table class objects.

from typing import List
from pydantic import BaseModel, Field


class Blackboard(BaseModel):
    size = 4000
    color: str = Field(..., alias='yanse',
                       description='the color of the blackboard, you can choose green or black.')


class Table(BaseModel):
    position: str


class ClassRoom(BaseModel):
    blackboard: Blackboard
    tables: List[Table]


m = ClassRoom(
    blackboard={'color': 'green'},
    tables=[{'position': 'first row, left 1'}, {'position': 'first row, left 2'}]
)

I got an error :

File "pydantic\main.py", line 342, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for ClassRoom
blackboard -> yanse
  field required (type=value_error.missing)

I want to know how could I correctly use Field class.

Thanks

I expect to have no error.

2
  • 1
    You gave it an alias, so you should use the alias. Commented Dec 28, 2022 at 8:31
  • Thank you. After using the alias, the problem is solved! Commented Dec 28, 2022 at 8:33

2 Answers 2

2

You are using an alias for the color field in your schema and filling your data with python dictionaries.

in this case, you should replace:

blackboard={'color': 'green'}

with:

blackboard={'yanse': 'green'}

The color field is used when you have a python schema object, not in dictionaries.

Sign up to request clarification or add additional context in comments.

Comments

0

In case you wanted to populate your Blackboard model using color, you can activate allow_population_by_field_name option in the Blackboard config options as follow:

class Blackboard(BaseModel):
    size = 4000
    color: str = Field(..., alias='yanse',
                       description='the color of the blackboard,
                        you can choose green or black.')

    class Config:
          allow_population_by_field_name = True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.