django serialize code example
Example 1: serialization in django
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.
Example 2: python serialize
import json
info = {
"data": {
"name": "Dave",
"City": "NY"
}
}
# With json.dump (into file)
with open( "data.json" , "w" ) as x:
json.dump( info , x )
# >>> {"data": {"name": "Dave", "City": "NY"}}
# with json.dumps (object)
data = json.dumps( info )
print( data )
# >>> {"data": {"name": "Dave", "City": "NY"}}