42

I want to have a total read only ModelSerializer, i.e. just list/retrieve methods

what is the best way to do it?

2
  • 1
    Is that what you want or do you want to remove the create/update from the view sets ?
    – Linovia
    Jul 12, 2016 at 6:25
  • 3
    good point @Linovia, actually im looking for ReadOnlyModelViewSet
    – Mohsen
    Jul 13, 2016 at 6:31

6 Answers 6

44

You really want to do this at the view (or Viewset) level, which you can do with a ReadOnlyModelViewSet.

(You mentioned this in your comment but I'm leaving it as an answer for better visibility).

For example (from the documentation):

from rest_framework import viewsets


class AccountViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A simple ViewSet for viewing accounts.
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
28

If you do need a serializer to be read only, it's most concise and stable option to override the init method:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    setattr(self.Meta, 'read_only_fields', [*self.fields])

In comparison with the above:

  • @mgalgs's solution is best, if a view irrespective of the serializer used should be read only.
  • @thisisms solution is best if you only have a few and non-dynamic fields
  • @D W's approach will only work if there are no writable serializer fields that use the 'source' keyword.

EDIT better solution: You can update the def get_fields method instead of the init method and create an abstract serializer:

class ReadOnlyModelSerializer(serializers.ModelSerializer):
    def get_fields(self, *args, **kwargs):
        fields = super().get_fields(*args, **kwargs)
        for field in fields:
            fields[field].read_only = True
        return fields

To use it, just inherit from the abstract serializer:

def MySerializer(ReadOnlyModelSerializer):
   class Meta:
       model = MyModel
       fields = '__all__'
2
  • 2
    This is a great solution which doesn't use any private fields, and is extensible - if you have a lot of read-only serializers, this could be used in a base class.
    – tbm
    May 7, 2020 at 14:50
  • 1
    @tbm indeed, I edited my answer to include an alternative solution using an abstract serializer class. Oct 4, 2020 at 17:01
17

The only thing you have to do is create a serializer like this. serializers.py

class YourdataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Yourdata
        # some data
        fields = ('id', 'city', 'pincode', 'created')
        read_only_fields = ('id', 'city', 'pincode', 'created')

Views something like this

class YourdataList(APIView):
    def get(self, request, format=None):
        yourdata = YourdataList.objects.all()
        serializer = YourdataSerializer(yourdata, many=True)
        return Response(serializer.data)

detail view

class YourdataDetail(APIView):
   def get_object(self, pk):
        try:
            return Yourdata.objects.get(pk=pk)
        except Yourdata.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = YourdataSerializer(snippet)
        return Response(serializer.data)

This will do it.

1
  • 10
    One way to make this a little more streamlined is to have read_only_fields = fields in Meta. Apr 27, 2017 at 15:42
14

If you're using a ModelSerializer you can achieve this with the following:

from rest_framework import serializers


class MyModelSerializer(serializers.ModelSerializer):
    ...

    class Meta:
        model = MyModel
        fields = ("field_1", "field_2", etc)
        read_only_fields = [f.name for f in MyModel._meta.get_fields()]

This solution uses the private _meta interface of the django model, but it's fairly stable and it's used fairly extensively by developers.

Here we're simply generating a list of all the fields in the relevant model and applying it to the read_only_fields option from django-rest-framework.

I prefer doing this at the serializer level as opposed to the view level as it doesn't tie you down to using Viewset's as suggested by mgalgs.

If you wanted to take this a step further, you could even wrap the functionality into a mixin which adds to the Meta options of your class. Something such as:

from rest_framework import serializers
from rest_framework.fields import Field


class ReadOnlyMixin(Field):

    def __new__(cls, *args, **kwargs):
        setattr(
            cls.Meta,
            "read_only_fields",
            [f.name for f in cls.Meta.model._meta.get_fields()],
        )
        return super(ReadOnlyMixin, cls).__new__(cls, *args, **kwargs)


class MyModelSerializer(ReadOnlyMixin, serializers.ModelSerializer):
    ...

    class Meta:
        model = MyModel
        fields = ("field_1", "field_2", etc)
1

Ok dear Mohsen,To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation()method. Let's take a look at an example using a simple Django model:

class HighScore(models.Model): 
 created = models.DateTimeField(auto_now_add=True) 
 player_name=models.CharField(max_length=10) 
 score = models.IntegerField()

It's simple to create a read-only serializer for converting HighScore instances into primitive data types.

class HighScoreSerializer(serializers.BaseSerializer):
 def to_representation(self, obj): 
  return { 'score': obj.score,  'player_name': obj.player_name }
3
  • look at my comment on my own post. thank you Hamed,
    – Mohsen
    Jul 13, 2016 at 6:40
  • 1
    Thats depend on view but your answer was about read only serializers Jul 13, 2016 at 11:23
  • I was initially looking for a solution in Serializer level, but its more natural to handle it in view level, and there is ReadOnlyModelViewSet for that
    – Mohsen
    Jul 14, 2016 at 4:37
1

two solutions for this?

from rest_framework.utils import model_meta

class CustomSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        model = getattr(self.Meta, 'model')
        declared_fields = copy.deepcopy(self._declared_fields)
        info = model_meta.get_field_info(model)
        field_names = self.get_field_names(declared_fields, info)
        _, hidden_fields = self.get_uniqueness_extra_kwargs(
        field_names, declared_fields, extra_kwargs)
        fields_names.extend(hidden_fields.keys())
        setattr(self.Meta, 'read_only_fields', list(field_names))

or

class CustomSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__()
        setattr(self.Meta, 'read_only_fields', list(self.fields))
1
  • 2
    read_only_fields = fields this also works if fields is not 'all'
    – Aseem
    Jun 13, 2021 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.