Difference between fields and read_only_fields in ModelSerializer

I am writing a serializer for my model which inherits serializers.ModelSerializer.
I only have one field to serialize.
I am curious to know if I have to put that field in both fields and read_only_fields.
I am using that serializer in APIView only for get method.
What actually happends behind if I put a field in read_only_fields?
I read the django-restframework documentation but did not understand the point.

Thanks in advance.

My take on it is that they serve two different purposes.

Listing the fields in the fields attribute identify which fields to include on a retrieval.

Listing the fields in read_only_fields would prevent fields from being changed in an update. The section on Specifying read only fields implies to me that it’s the same as specifying editable=False on each field or having the field defined as an AutoField.

If you’re only providing a read-only access, then I don’t see where the read_only_fields attribute will do anything at all.

Understood.
So I think I don’t need to add the field to read_only_fields if I only provide GET method for API.
What do you think?

That’s my understanding, yes.

Okay
That makes sense

Thank you again. :slight_smile:

Hi, Ken!

I think I still need to add my field to read_only_fields.
If I don’t do that, that field is filterable.
For my case, I should not allow that.

Regards. :wink:

You’ve got me curious here - what do you mean by filterable for this? (Are you generating a response using an APIView class? Implementing only a get method? Using any mixins with your class?)

I am using swagger in my Django project and use that to test APIs.
Excluding the field from read_only_fields resulted that field available for parameter of GET request.
Anyway it;s not an issue.

I created another topic which might interest you