Reputation: 179
I am just learning Django and Django Ninja API. I have created a simple Api to create and read object(s).
models.py
class Person (models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
schemas.py
class PersonIn(ModelSchema):
class Config:
model = Person
model_fields = ["first_name", "last_name"]
class PersonOut(ModelSchema): # Just to make it clear
class Config:
model = Person
model_fields = ["first_name", "last_name"]
api.py
@router.post("/person")
def create_person(request, payload: PersonIn):
data = payload.dict()
try:
person, created = Person.objects.update_or_create(**data)
except Exception:
return { "mesg": "Some error happened"}
@router.get("/persons", response = list[PersonOut])
def get_persons(request):
p = get_list_or_404(Person)
return p
views.py
def get_persons_view(request):
persons = ???
render(request,"personlist_template.html", {"persons": persons})
If I import the function api, then it returns Person Model object rather than serialized object in the form of PersonOut.
I wanted to use the api call in way that it returns the serialized form as being called through API url. This way I am attempting to
I found 2 methods for objective 2.
One is using Django Serializers. In this case I need to have separate method, if I am serializing single model isntance.
from django.core import serializers
data = serializers.serialize("json", Person.objects.all())
Or using method Person.Objects.values()
or another methods e.g. models.model_to_dict or writing custom DjangoJSONEncoder. But, that is just extra coding, when I have already implemented that in API.
I am assuming there is some straight forward to call that api function inside a view where the decorator magic of Ninja works. Just cannot find it.
Upvotes: 1
Views: 1389
Reputation: 6724
The docs you are looking for can be found here: https://django-ninja.rest-framework.com/guides/response/?h=from_orm#serializing-outside-of-views
Inside your view, you can do something like this:
output = [PersonOut.from_orm(person).dict() for person in persons]
The output should now contain something like:
[{'first_name': 'John', 'last_name': 'Doe'}, {'first_name': 'Jane', 'last_name': 'Doe'}]
I hope this helps.
Upvotes: 0
Reputation: 5821
maybe this can work for you
def serialize(schema_cls, queryset):
items = [schema_cls.from_orm(i).dict() for i in queryset]
return json.dumps(items)
...
persons = serialize(PersonOut, Person.objects.all())
Upvotes: 0