How to use Pydantic base schema to n number of child schema

Viewed 365

I'm new to pydantic, I want to define pydantic schema and fields for the below python dictionary which in the form of JSONAPI standard

{
  "data": {
    "type": "string",
    "attributes":{
           "title": "string",
           "name": "string"
          }
}

I managed to achieve this by defining multiple schemas like below,

class Child2(BaseModel):
    title: str
    name: str

class Child1(BaseModel):
    type: str
    attributes: Child2

class BaseParent(BaseModel):
    data: Child1

But, I will be having multiple json request with the same json API structure as below,

example 1 {
  "data": {
    "type": "string",
    "attributes":{
           "source": "001",
           "status": "New"
          }
}

example 2 {
  "data": {
    "type": "string",
    "attributes":{
           "id": "001"
          }
}

If you look into the above python dictionary, Values only under the attributes object are different. So, is there any way that I can define a parent marshmallow scheme for { "data": { "type": "string", "attributes":{ } } } and use that parent schema for all child schema's.

1 Answers

I found an answer finally, Hope this will help someone.

Pydantic 'create_model' concept will help to resolve this kind of requirement by passing child schema as one of the field values to create_model.

class Child(BaseModel):
   title: str
   name: str
 
class BaseParent(BaseModel):
    data: create_model('BaseParent', type=(str, ...), attributes=(Child, ...))

And this will frame a BaseParent schema structure as below,

data=BaseParent(type='id', attributes=Child2(title='test002', name='Test'))
Related