1👍
I believe you have the answer in the DRF docs: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
SerializerMethodField This is a read-only field…It can be used to add any sort of data to the serialized representation of your object.
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
days_since_joined = serializers.SerializerMethodField()
class Meta:
model = User
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
Update: Now for your case:
class PostSerializer(serializers.ModelSerializer):
postType = serializers.SerializerMethodField()
class Meta:
model = Post
fields = ('id', 'usersVoted', 'post')
read_only_fields = ('id', 'owner')
def get_postType():
return "posts"
0👍
You got that exception because read_only_fields
are supposed to be from the model while postType
isn’t a model field.
- Is it possible for django-rest-framework view to be called without a request object?
- Django: How do I create a view to update multiple records on an intermediate model with a Many-to-Many-through relationship?
- Error Making POST to ServiceM8
Source:stackexchange.com