serializers, a serialization tool that comes with django
Three Steps
- Import from django.core import serializers
- Generate object and pass response = serializers.serialize('json', book_list)
- The first json is a parser that says you want to parse a string in json format.
- The second is the queryset object.
- Finally returns the result return JsonResponse(response, safe=False)
- safe for false is not a formal json format, it may contain list tuples and other format strings
from app01 import models from django.shortcuts import render, HttpResponse from django.core import serializers from django.http import JsonResponse from rest_framework.views import APIView class BookManage(APIView): def get(self, request, *args, **kwargs): book_list = models.Book.objects.all() # serialize(format, queryset, **options) # Format, pass queryset object, other options response = serializers.serialize('json', book_list) # safe=False If this is not set when there are other lists in the dictionary, an error will be returned return JsonResponse(response, safe=False) //As shown below, too many fields in the dictionary are useless and can cause network congestion
Simple use of Serilizer for drf
Three Steps
- Import from rest_framework import serializers
- Write a class that inherits serializers.Serializer
- class BookSerializers(serializers.Serializer)
- Generate object bsl = BookSerializers(instance=book_list, many=True) in class method
- many=true indicates that there are multiple queryset objects.
- many=false indicates that there is only one data in the dictionary
from app01 import models from django.shortcuts import render, HttpResponse from django.http import JsonResponse from rest_framework.views import APIView from rest_framework import serializers # Create your views here. class BookSerializers(serializers.Serializer): # It is important to note that the value of this serialization component must be a value that exists in the dictionary in the serialization!! name = serializers.CharField() price = serializers.DecimalField(max_digits=5, decimal_places=2) class BookManage(APIView): def get(self, request, *args, **kwargs): book_list = models.Book.objects.all() # Initialization method def u init_ (self, instance=None, data=empty, **kwargs) # Many has more than one if he passes true, kwargs.pop('many', None) # many passes false instructions with only one dictionary bsl = BookSerializers(instance=book_list, many=True) return JsonResponse(bsl.data, safe=False)
[{"name": "1111", "price": "11.11"}, {"name": "2222", "price": "22.22"}]
If you don't want one of the results, comment or delete it directly in the serializers # name = serializers.CharField() after commenting it [{"price": "11.11"}, {"price": "22.22"}, {"price": "33.33"}, {"price": "44.44"}]
Methods under Serializer under drs
source attribute
-
Change the name of foreground view source="name"
class BookSer(serializers.Serializer): bookname = serializers.CharField(source="name") The dictionary in the foreground changes the name to "bookname": "python".
-
Multi-table operation
-
Add u str_u to Table Model
When the current background dictionary returns directly as the result of an object, the background only needs to change the source "publish": "Publish object (2)" Model additions for models def __str__(self): return self.name
-
Specify fields using source
Refers to a segment that exists in a thesaurus model, and this publish can be changed if it has a source publish = serializers.CharField(source='publish.city') source="publish.city" The final query is a book.publish.city query
-
Add a method to the table model
Add a method to the table model of the returned object and query directly in serializers using source def get_city(self): return self.city publish = serializers.CharField(source='publish.get_city')
-
SerializerMethodField
-
Custom Method
authors = serializers.SerializerMethodField() # A parameter needs to be passed, which is actually the return result book_obj from background views # msg = BookSer(book_obj, many=True) def get_authors(self, book): msg = [{"author_name": author.name, "age": author.age} for author in book.authors.all()] return msg # List generation, the result is {"publish":"xx Press", "authors": [ {"name":"xx", "age":11}] }
-
Serialize the results of the query directly
class Authors(serializers.Serializer): name = serializers.CharField() age = serializers.IntegerField() class BookSer(serializers.Serializer): # A method can be specified using SerializerMethodField authors = serializers.SerializerMethodField() def get_authors(self, book): auth_obj = book.authors.all() msg = Authors(auth_obj, many=True) return msg.data # The result is the same as the list generation
ModelSerializer under drs
fields method
-
Get All
# All fields under this table will be shown in the foreground class BookSer(serializers.ModelSerializer): # This is a fixed format class Meta: model = models.Book fields = "__all__"
-
Similar to whitelist
class BookSer(serializers.ModelSerializer): # This is a fixed format class Meta: model = models.Book fields = ["nid","publish"] # Just these two # If a custom value is written, then the name needs to be the same as defined in fields publish = serializers.CharField(source="publish.name")
-
Similar to blacklist, filter, cannot coexist with fields
class BookSer(serializers.ModelSerializer): # This is a fixed format class Meta: model = models.Book exclude = ["authors"] # Filter it out
-
Query Depth
class BookSer(serializers.ModelSerializer): # This is a fixed format class Meta: model = models.Book fields = "__all__" # The official recommendation is not to exceed 10 levels of depth, one level at a time, and it is best not to exceed 3 levels in practice depth = 1 sqlite If there is time to query, there will be a very long error prompt
Methods under Meta
-
override method
# All fields under this table will be shown in the foreground class BookSer(serializers.ModelSerializer): # This is a fixed format class Meta: model = models.Book fields = "__all__" # Rewrite method under Meta publish = serializers.CharField(source="publish.name")
-
You can also use serialization
authors = serializers.SerializerMethodField() def get_authors(self, obj): auth = obj.authors.all() msg = Authors(auth, many=True) return msg.data