Home > Enterprise >  django custom serializer field not working
django custom serializer field not working

Time:07-26

I am trying to add an additional field in the serializer but at the moment of adding it I get the following error error view

During handling of the above exception ('MovieSerializer' object has no attribute 'len_name')

I have seen many posts and all of them are working, what could it be?

this is my code

Model:

from django.db import models

class Movie(models.Model):
    title = models.CharField(max_length=255, unique=True)
    description = models.TextField()
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(default=None, null=True)

    def __str__(self):
        return self.title

serializer:

from rest_framework import serializers
from watchlist_app.models import Movie
from watchlist_app.api.validations import MovieValidations


class MovieSerializer(serializers.ModelSerializer):
    len_name = serializers.SerializerMethodField(method_name='len_name')

    class Meta:
        model = Movie
        fields = "__all__"
        read_only_fields = ['id', 'len_name', 'created_at']
        required_fields = ['title', 'description']

        @staticmethod
        def create(self, validated_data):
            return Movie.objects.create(**validated_data)

        @staticmethod
        def update(self, instance, validated_data):
            instance.title = validated_data.get('title', instance.title)
            instance.description = validated_data.get('description', instance.description)
            instance.active = validated_data.get('active', instance.active)
            instance.save()
            return instance

        @staticmethod
        def get_len_name(self, obj):
            return len(obj.title)

        validators = [MovieValidations.validate_title, MovieValidations.validate_description,
                      MovieValidations.validate_equals]
        

everything works fine until I add the serializerMethodField

CodePudding user response:

use extra_fields in meta class

class MovieSerializer(serializers.ModelSerializer):
    len_name = serializers.SerializerMethodField(method_name='len_name')

    class Meta:
        model = Movie
        fields = "__all__"

        extra_fields = ['len_name',]

        read_only_fields = ['id', 'len_name', 'created_at']
        required_fields = ['title', 'description']

*** your serializer methods in wrong indent,fix it -> Go back one indent and remode staticmethod decorator ***

CodePudding user response:

I think you set the function in the wrong place. The function needs to belong to the MovieSerializer.

from rest_framework import serializers
from watchlist_app.models import Movie
from watchlist_app.api.validations import MovieValidations    

class MovieSerializer(serializers.ModelSerializer):
    len_name = serializers.SerializerMethodField()

    class Meta:
        model = Movie
        fields = "__all__"
        ...

    def get_len_name(self, obj):
        return len(obj.title)
  • Related