serialization in django
from rest_framework import serializers
from .models import Product
class ProductSerializers(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
# Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types.
# Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
It is just a method of converting a type of data into another, most probably in
text format, and in dictionary or into a human managable form
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks.
Serializers also provide deserialization, allowing parsed data to be converted back into complex types,
after first validating the incoming data.
serialization in django
from rest_framework import serializers
from .models import Student
class ProductSerializers(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
#in views.py
from django.shortcuts import render
from .serializers import StudentSerializer
from django.http import HttpResponse
from .models import Student
from rest_framework.renderers import JSONRenderer
# Create your views here.
def students(request):
stu = Student.objects.all()
# stu = Student.objects.get(id=2) to get one object
# serializer = StudentSerializer(stu) we dont need many=True
serializer = StudentSerializer(stu, many=True)
json_data = JSONRenderer().render(serializer.data)
print(serializer)
return HttpResponse(json_data, content_type ='application/json' )