django-ninja
django-ninja copied to clipboard
serialization without a view?
Please describe what you are trying to achieve
I have some places in my code where I need to get at a JSON version of an object that aren't within the API. Is there some way to take advantage of the Schemas I've defined to convert?
Please include code examples (like models code, schemes code, view function) to help understand the issue
from ninja.hope_this_exists import serialization_helper
class Job(models.Model):
...
class JobOut(Schema):
...
job = Job.objects.get(id=1)
serialized = serialization_helper(JobOut, job)
Hi @cltrudeau
Use .from_orm
+ .dict
or .json
methods:
job = Job.objects.get(id=1)
data = JobOut.from_orm(job)
data.dict() # will return python dict (that can be converted to json)
data.json() # will return string (with json)
Perfect thanks.
I notice the .from_orm
method doesn't appear to be mentioned in the docs. Happy to make an MR. Maybe something in the "Response Schema" section?
@cltrudeau sure - go ahead
@vitalik how does from_orm
works with queryset?
I have been qurious since I l faced #495 issue.
@quroom
qs = Job.objects.all()[:100]
result = [JobOut.from_orm(i).dict() for i in qs]
Docs got added. As it was only documentation I was lazy and didn't build anything. Hopefully I didn't break anything :)
Hi @cltrudeau,
If your issue was resolved would you mind closing down this issue? ( its hard to get actual bugs in a pile of issues )