django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

serialization without a view?

Open cltrudeau opened this issue 2 years ago • 6 comments

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)

cltrudeau avatar Jul 06 '22 18:07 cltrudeau

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)

vitalik avatar Jul 07 '22 08:07 vitalik

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 avatar Jul 07 '22 13:07 cltrudeau

@cltrudeau sure - go ahead

vitalik avatar Jul 07 '22 13:07 vitalik

@vitalik how does from_orm works with queryset? I have been qurious since I l faced #495 issue.

quroom avatar Jul 08 '22 01:07 quroom

@quroom

qs = Job.objects.all()[:100]

result = [JobOut.from_orm(i).dict() for i in qs]

vitalik avatar Jul 08 '22 07:07 vitalik

Docs got added. As it was only documentation I was lazy and didn't build anything. Hopefully I didn't break anything :)

cltrudeau avatar Jul 11 '22 14:07 cltrudeau

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 )

baseplate-admin avatar Apr 02 '23 04:04 baseplate-admin