# serialization in django
from rest_framework import serializers
from .models import Product
class ProductSerializers(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
# adding extra fields, that are in models
def to_representation(self, instance):
data = super().to_representation(instance)
data['is_on_sale'] = instance.is_on_sale()
data['current_price'] = instance.current_price()
return data
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
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' )