I want to have a total read only ModelSerializer
, i.e. just list/retrieve methods
what is the best way to do it?
I want to have a total read only ModelSerializer
, i.e. just list/retrieve methods
what is the best way to do it?
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
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:
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__'
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.
read_only_fields = fields
in Meta
.
Apr 27, 2017 at 15:42
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)
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 }
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))