Basic concepts of SerializerMethodField
definition:
-
SerializerMethodField
It is a special field type provided by Django REST framework. - It allows you to define a method to dynamically get and return a field value in a serialized data that can generate return values based on other properties of the model instance, associative model, or any custom logic.
use:
- When you need to include some information in the serialized data that cannot be directly retrieved from the model field, or you need to perform special processing on the model field (such as formatting dates, splicing strings, etc.) before returning,
SerializerMethodField
It's very useful. - For example, calculate the sum of two fields in a model instance, obtain a combination of attributes of the associated model, etc.
Steps to Using SerializerMethodField
Step 1: Define in the serializerSerializerMethodField
from rest_framework import serializers import Product class ProductSerializer(): total_price = () class Meta: model = Product fields = ['price', 'tax', 'total_price']
Suppose you have oneProduct
Model, includingprice
andtax
Two fields, you want to include one in the serialized datatotal_price
field, the value of this field isprice
Plustax
value.
First, inDefine the serializer in the file:
heretotal_price
Defined asSerializerMethodField
, it tells the serializer that the value of this field needs to be obtained through a custom method.
Step 2: Define the method to obtain field values
class ProductSerializer(): total_price = () def get_total_price(self, product): return + class Meta: model = Product fields = ['price', 'tax', 'total_price']
existProductSerializer
In the class, you need to define a method to obtaintotal_price
The value of the field.
The naming rules for this method areget_<field_name>
,in<field_name>
yesSerializerMethodField
The field name defined.
In this example, the method name isget_total_price
:
- this
get_total_price
Method to receive aproduct
Object (that is, currently being serializedProduct
Model instance) as parameter, then returnprice
andtax
The sum of the field values. - This return value will be
total_price
The value of the field in the serialized data.
Step 3: Use the serializer in the view
from rest_framework.viewsets import ModelViewSet import ProductSerializer import Product class ProductViewSet(ModelViewSet): queryset = () serializer_class = ProductSerializer
Use this serializer in a view function or view set.
For example, in a class-based view set:
- When this view set processes the request,
ProductSerializer
Will be matched in the defined wayProduct
The model instance is serialized. - for
total_price
Fields will be calledget_total_price
Method to get the value and include it in the serialized data.
Application of SerializerMethodField in Associative Model
Handle one-to-many relationships:
Assume you haveAuthor
andBook
Two models, oneAuthor
How many books can beBook
, and you want to serializeAuthor
when including the title list of all its books.
from import models class Author(): name = (max_length=100) class Book(): title = (max_length=200) author = (Author, on_delete=)
from rest_framework import serializers import Author, Book class BookSerializer(): class Meta: model = Book fields = ['title'] class AuthorSerializer(): book_titles = () def get_book_titles(self, author): books = author.book_set.all() return [ for book in books] class Meta: model = Author fields = ['name', 'book_titles']
The model is defined as follows:
existDefine the serializer in:
- here
AuthorSerializer
In-housebook_titles
Field passesSerializerMethodField
To get the current oneAuthor
All associatedBook
list of titles. -
get_book_titles
Method GettingAuthor
All associatedBook
instance, then extract eachBook
oftitle
field value, and finally return a title list asbook_titles
The value of the field.
Handle many-to-many association relationships (similar logic):
- If it is a many-to-many relationship, for example
Student
andCourse
The course selection relationship between models, in serializationStudent
If you want to include a list of names of selected courses, you can use a similar method. - It is just that when obtaining the data of the association model, you need to pay attention to the processing of many-to-many relationships (usually through
many - to - many
attributes to get the associated model collection).
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.