Home > Enterprise >  How to use different Pydantic Models in a view
How to use different Pydantic Models in a view

Time:11-26

Im currently trying to understand the Pydantic FastAPI setup within my Django app and have the following issue:

When I create a new Order object, I want to return the newly created object using a different Pydantic model as I use for the creation (as after the creation I now have the ID of the order that I can also return).

# routes

# Create a new Order
@router.post("/create/", response_model=schemas.OrderResponse)
def create_orders(order: schemas.OrderBase):
    return views.create_order(order=order)
# views.py

from uuid import UUID
from . import models, schemas


# Create a new order
def create_order(order: schemas.OrderBase):
    new_order = models.Order.objects.get_or_create(order)
    return new_order
# schemas.py
# pydantic models

from uuid import UUID
from pydantic import BaseModel


# Base Class for Model "Order"
class OrderBase(BaseModel):
    product: str
    period: str
    power: int
    side: str

    class Config:
        orm_mode = True


class OrderResponse(OrderBase):
    id: UUID

When I now send an API request with this body:

{
    "product": "Base",
    "period": "Hour",
    "power": 10,
    "side": "Buy"
}

I get this error -- how to set it up such that when creating the instance it doesnt validate for the UUID and after creation and when returning the instance it includes the UUID in the response?

pydantic.error_wrappers.ValidationError: 5 validation errors for OrderResponse
response -> product
  field required (type=value_error.missing)
response -> period
  field required (type=value_error.missing)
response -> power
  field required (type=value_error.missing)
response -> side
  field required (type=value_error.missing)
response -> id
  field required (type=value_error.missing)

CodePudding user response:

It seems like converting your django model instance to pydantic automatically is not supported on fastAPI. So I add a code that convert your model to dict, and that dict will initiate OrderResponse instance.

Try this,

from django.forms.models import model_to_dict

...
@router.post("/create/", response_model=schemas.OrderResponse)
def create_orders(order: schemas.OrderBase):
    return model_to_dict(views.create_order(order=order))
  • Related