Solved: django serializer method field read write

The main problem with the serializer’s field read write is that it can be easily abused. For example, if you have a model that stores user data in a field called “name”, you could easily create a serializer method that reads the user’s name from the database and writes it to the model’s “name” field. This would allow you to access the user’s name from any view or template in your application, without having to query the database each time.

I am trying to create a method field in my Django serializer that will read and write data. The field is called "status" and I want it to return "active" if the user has an active subscription, and "inactive" if they do not.
Here is my code:
class UserSerializer(serializers.ModelSerializer):

status = serializers.SerializerMethodField()

def get_status(self, obj):
if obj.subscription_set.filter(is_active=True).exists():
return 'active'
else:
return 'inactive'

class Meta:
model = UserProfile
fields = ('username', 'email', 'first_name', 'last_name', 'status')

def update(self, instance, validated_data):

instance.username = validated_data['username']
instance.email = validated_data['email']

if validated_data['password']: # password can be empty string when updating user profile without changing password (e-mail only) - https://github.com/tomchristie/django-rest-framework/issues/3086#issuecomment-290987912 - thanks @encode! :) # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=C0301 # noqa E501 (line too long) pylint: disable=C0301 # noqa E501 (line too long) pylint: disable=C0301 # noqa E501 (l... instance.set_password(validated_data['password'])

instance.save()

return instance

The error I am getting is this one when I try to save the data with a PUT request in Postman or Insomnia REST client - "detail": "Method "PUT"" not allowed."" This happens even though I have added the update() method in my code above as suggested by other SO posts on similar topics like this one here Django Rest Framework Serializer Method Field Update Issue . Any help would be appreciated! Thanks! 🙂

Related posts:

Leave a Comment