SoFunction
Updated on 2025-04-13

Detailed explanation of the use of SerializerMethodField in Django serialization

Basic concepts of SerializerMethodField

definition

  • SerializerMethodFieldIt 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,SerializerMethodFieldIt'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 oneProductModel, includingpriceandtaxTwo fields, you want to include one in the serialized datatotal_pricefield, the value of this field ispricePlustaxvalue.

First, inDefine the serializer in the file:

heretotal_priceDefined 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']

existProductSerializerIn the class, you need to define a method to obtaintotal_priceThe value of the field.

The naming rules for this method areget_<field_name>,in<field_name>yesSerializerMethodFieldThe field name defined.

In this example, the method name isget_total_price

  • thisget_total_priceMethod to receive aproductObject (that is, currently being serializedProductModel instance) as parameter, then returnpriceandtaxThe sum of the field values.
  • This return value will betotal_priceThe 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,ProductSerializerWill be matched in the defined wayProductThe model instance is serialized.
  • fortotal_priceFields will be calledget_total_priceMethod to get the value and include it in the serialized data.

Application of SerializerMethodField in Associative Model

Handle one-to-many relationships

Assume you haveAuthorandBookTwo models, oneAuthorHow many books can beBook, and you want to serializeAuthorwhen 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:

  • hereAuthorSerializerIn-housebook_titlesField passesSerializerMethodFieldTo get the current oneAuthorAll associatedBooklist of titles.
  • get_book_titlesMethod GettingAuthorAll associatedBookinstance, then extract eachBookoftitlefield value, and finally return a title list asbook_titlesThe value of the field.

Handle many-to-many association relationships (similar logic)

  • If it is a many-to-many relationship, for exampleStudentandCourseThe course selection relationship between models, in serializationStudentIf 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 throughmany - to - manyattributes 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.