Migrating from FastAPI, using Pydantic Models (e.g. BaseModel) directly OK? #1555
-
|
Hi all, I have a FastAPI service I want to migrate to Django Ninja, ultimately so I can bolt this service onto something larger with an ORM etc already configured. I don't want to pre-emptively convert all the Pydantic models to Django Ninja schemas, and looking at the source code + testing locally, it seems like I can just use my existing Pydantic schemas without modification. It seems like So It looks like I can just copy my pydantic models across and be happy in Django land (until I have time to make things consistent). Anything I'm missing? Cheers! Here's my sample api (everything else is a basic Django starter app with most of the built-in apps and middleware removed): from ninja import NinjaAPI, Query
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_pascal
from scalar_django_ninja import ScalarViewer
api = NinjaAPI(
version="1.0.0",
title="API Reference",
description="API Reference for the Scalar Django Ninja Plugin",
docs=ScalarViewer(),
docs_url="/openapi/",
)
class Visitor(BaseModel):
name: str = "Stranger"
class Greeting(BaseModel):
message: str
model_config = ConfigDict(alias_generator=to_pascal)
@api.get("/add")
def add(request, a: int, b: int):
return {"result": a + b}
@api.get("/greet")
def greet(request, visitor: Query[Visitor]) -> Greeting:
return Greeting(Message=f"Hello, {visitor.name}")
@api.post("/greet")
def greet_post(request, visitor: Visitor) -> Greeting:
return Greeting(Message=f"Hello, {visitor.name}") |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
@christianmhubble - yes Schema is a subclass of BaseModel that just adds some extras (and hides the "model" word as it's has different meaning in django world(db table) so yeah - if you just copy pydantic models and use them in django-ninja - all will work |
Beta Was this translation helpful? Give feedback.
@christianmhubble - yes Schema is a subclass of BaseModel that just adds some extras (and hides the "model" word as it's has different meaning in django world(db table)
so yeah - if you just copy pydantic models and use them in django-ninja - all will work