Comments (10)
So it looks like ninja calls model_validate
even if the endpoint returns an instance of the response schema. I'm not sure if this is something that's changed since last version, but I've made a fix for it. Can I get you to test if the change returns you to normal speed?
Change lines 206-210 in ninja/operation.py to the below:
response_type = response_model.__annotations__["response"]
if isinstance(response_type, Schema) and isinstance(result, response_type):
validated_object = response_model.model_construct(response=result)
else:
resp_object = ResponseObject(result)
validated_object = response_model.model_validate(
resp_object, context={"request": request, "response_status": status}
)
from django-ninja.
Thanks for the suggestions, @OtherBarry. I suspected that that was the case as well, since returning Schema
s directly isn't something I've seen in the docs, and in the code I believe it's just checking for Manager
s, QuerySet
s, and dicts. I actually tried returning a Django HttpResponse
directly, since that circumvents Ninja's response logic, but unfortunately that didn't improve things either (which is another reason I'm guessing the bottleneck is in the Schema
logic somewhere). I'll give your workaround a try though.
EDIT: No appreciable improvement with the workaround.
Another thing that may be worth mentioning: I don't see this slowdown when Pydantic v2 is used with FastAPI. I maintain a lot of FastAPI services, and when I first noticed this in Ninja v1 I was worried it might be affecting all our other services. After testing it though, the speed and throughput appeared the be no different with or without response generation by alias.
from django-ninja.
@vitalik, any suggestions?
from django-ninja.
did you try returning non validated objects ( I did not investigate this deeply - but most likely it just does double validation)
try this
@api.get('/examples', response=ExampleListSchema, by_alias=True)
def list_examples(request: HttpRequest, **kwargs) -> dict:
return {"examples": Example.objects.all()}
from django-ninja.
I haven't, but thanks for the suggestion. I'll give that a try and report back.
from django-ninja.
Ok, tried that out basically exactly as you suggested, and while it did improve the response time, it's still approximately 3x slower than with Django-Ninja<1.0 (~150ms vs. ~50ms).
Not sure if this could have anything to do with it, but for what it's worth, the real endpoint and database query I'm testing here JOIN
s 3 other tables in (which I'm doing with select_related()
).
Thanks again for your help on this, I really appreciate it.
from django-ninja.
Have you tested that there aren't any database calls being made as part of the validation?
from django-ninja.
There shouldn't be, since the validation is just standard Pydantic stuff (max length, etc.).
from django-ninja.
I was thinking more in terms of a field that you expect to be prefetched isn't, hence when pydantic goes to accesss the property, django fetches the value from the database in the background. Though with that much of a double validation difference, it's unlikely to be the issue, as the db hit should only happen once regardless of how many times it's validated.
from django-ninja.
I think that's unlikely, since the endpoint code is the same when I'm testing with the two versions. I'm using select_related()
for all three tables that are being joined, and a while back I tested it without those calls to verify that the query was faster with them.
from django-ninja.
Related Issues (20)
- Overriding JSON schema title and summary without using `Field` HOT 1
- [BUG] CSRF Fails with Django Auth HOT 16
- [BUG] Order of operations affect response and request schemas HOT 1
- Documentation - link the schema article to the error article
- Add description to tags HOT 2
- Field order issue in JSON response HOT 1
- [BUG] Allow specifying field types for custom fields
- [BUG] The other API URLs work, but the openapi docs don't appear. HOT 5
- [BUG] Can't use parameter `keys`
- how to add a description for query params that shows in the generated docs?
- Field with list factory causes API docs to not load with non-serializable. HOT 2
- Annotate Decimal field does not supported "Unable to serialize unknown type: <class 'ellipsis'"
- Traversing the data structures to create an HTTP API client HOT 3
- how to use token ? HOT 1
- Path parameters, order matters HOT 3
- [BUG] Combining JWTAuth with django_auth only works in that order
- [BUG] Pydantic 2.7.0 incompatibily HOT 4
- [BUG] ModelSchema with ManyToManyField won't work under async views HOT 5
- How do you use aliases with nested objects
- [BUG] HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-ninja.