Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

django custom serializer field not working


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


Solution

  • 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)