Skip to content

Document that explicitly declared fields will not have their attributes overridden by read_only_fields shortcut. #3460

Closed

Description

@TheProdigyFilippo
class PersonSerializer(serializers.ModelSerializer):
    info = serializers.Field(source='info')

    class Meta:
        model = Person
        read_only_fields = ('info',)

In this case read_only_fields is not working (info field is not read only) and we have to add read_only=True to the field. It's very confusing.

Activity

  1. jpadilla commented on Oct 1, 2015

    @jpadilla
    Contributor

    @TheProdigyFilippo I'm pretty sure you'll also need to set fields = ('info', ) as the example in the docs. Also, please note that the discussion group is the best place to take this discussion and other usage questions. Thanks!

  2. TheProdigyFilippo commented on Oct 1, 2015

    @TheProdigyFilippo
    Author

    @jpadilla Thank for your interest, but you're wrong. Firstly, in the documentation there's no written anywhere that read_only_fields should work only in conjuction with fields. And it shouldn't. Example is EXAMPLE only. If there would be additionaly some crappy global variable in the docs does it mean, that read_only_fields works only when you also use this global variable?

    read_only_fields is not working when you add field explicitly to the serializer class and it is a bug. Even adding this field to fields, what you proposed (but what is stupid) is not working. Real life example:

    class UserTransferSerializer(serializers.ModelSerializer):
        date = serializers.DateTimeField(format='%s')
    
        class Meta:
            model = Transfer
            fields = ('date', 'transfer_cost')
            read_only_fields = ('transfer_cost', 'date')

    And the result:

    s = UserTransferSerializer()
    >>> s.fields
    {'date': DateTimeField(format='%s'), 'transfer_cost': DecimalField(decimal_places=8, max_digits=18, read_only=True)}
    

    But why the necessity of adding explicitly created Field to the field tuple is stupid? Because you can use exclude which is mutually exclusive with fields and read_only_fields would be useless.

    I hope that now you understand the bug. If you have any more questions, I'll do my best to answer, give few more examples and so on. Of course you can also use the discussion group.

  3. xordoquy commented on Oct 1, 2015

    @xordoquy
    Contributor

    @TheProdigyFilippo please refrain from using aggressive tone. A few things to keep in mind:

    1. This is no paid support and we can't afford to spend hours on each issue.
    2. We do see on regular basis examples of DRF bugs that turns out to be user's bug.
    3. If you want to speed up this issue, feel free to provide a failing test case we can work on out of the box.
  4. TheProdigyFilippo commented on Oct 1, 2015

    @TheProdigyFilippo
    Author

    Dear @xordoquy @jpadilla, excuse me for my aggresive tone. It was response for treating me like a ingoramus and sending away to the docs (I've read it), discussion group and superfast closing this issue by Jose. I'm very sorry again for that. I wanted to help you guys, DRS still is great and your work also is great :)

  5. xordoquy commented on Oct 1, 2015

    @xordoquy
    Contributor

    The fact that we close pretty fast issues is linked with our bandwidth. Examples help but still require a lot of our time which is limited. A failing test case definitively helps understanding the issue and figure whether or not it's a DRF bug and whether or not it needs to be fixed.

  6. lovelydinosaur commented on Oct 1, 2015

    @lovelydinosaur
    Member

    In this case read_only_fields is not working

    Correct - if you've specified a field explicitly it doesn't make sense to have it in read_only_fields. We could as an enhancement error loudly?

  7. TheProdigyFilippo commented on Oct 1, 2015

    @TheProdigyFilippo
    Author

    if you've specified a field explicitly it doesn't make sense to have it in read_only_fields

    Can't agree with you. It would be definitely better (for a coding style) to take advantage of configuration in one place. In my example I'm forced to set read_only property in two places (in field and read_only_fields) or redefine all model fields in serializer and not use read_only_fields to achieve consistency. But it would be great to set read_only property for all wished fields in read_only_fields.

  8. xordoquy commented on Oct 1, 2015

    @xordoquy
    Contributor

    I think it'd be more consistent if read_only_fields would also apply to explicitly defined fields.
    After all, we do need to list them to the fields list so they are taken into account.
    The major issue I'd see to this change would be the following case:

    class PersonSerializer(serializers.ModelSerializer):
        info = serializers.Field(source='info', read_only=False)
    
        class Meta:
            model = Person
            read_only_fields = ('info',)
    
  9. carltongibson commented on Oct 1, 2015

    @carltongibson
    Collaborator

    We had this conversation when the API for 3.0 was being discussed. The summary of it was this:

    1. All these convenience flags would be removed, in order to promote a cleaner API.
    2. We'd make a special exception for read_only_fields — because it was such a common use-case.

    The use-case is when you have a ModelSerializer where you are not explicitly defining fields but quickly want to mark a field as read-only: the obvious example of this is a user field, where you set the user based on request.user and not on submitted data.

    We decided that once users stepped onto the path of explicitly defining fields they would be responsible for moving the read-only declaration there, in line with 1 above.

  10. lovelydinosaur commented on Oct 1, 2015

    @lovelydinosaur
    Member

    It would be definitely better (for a coding style) to take advantage of configuration in one place.

    Agree. And if the field has been defined explicitly - that's where.

    1. Drop read_only_fields entirely, because it's such an ugly little shortcut.
    2. Complain if an explicit field is in read_only_fields.
    3. Do nothing.

    But having an explicitly defined field that does not match the definition its been given isn't going to happen.

  11. carltongibson commented on Oct 1, 2015

    @carltongibson
    Collaborator

    Drop read_only_fields entirely, because it's such an ugly little shortcut.

    Just on this. It is (an ugly little shortcut) — but it's handy for newcomers to DRF: you can get up and running with ModelSerializer, and get some great results without learning too much. Then you realise need to make your user reference read-only and, without the shortcut, there's instantly a whole load of unfamiliar API that you need to take-in. With the shortcut you can keep progressing and loop back to the Fields API, a good while later.

  12. lovelydinosaur commented on Oct 1, 2015

    @lovelydinosaur
    Member

    Indeed, so we're not taking (1), and had really already made a decision on that. From my POV that leaves (2) and (3) as valid options.

  13. twbagustin commented on Mar 31, 2017

    @twbagustin

    So.. This ain't fixed yet right? Came here through Google.. I don't agree with dropping the shortcut, it's as it was pointed out a "common scenario". If you have a bunch of fields customized say 15 it feels kinda silly to place a read_only flag on each one vs using a shortcut that was actually created for this purpose... Specific use-case: I have a django live production model with a lot of fields, you need the api to throw camelCase field names, so you have to explicitly set each field to rename it, and mark them read_only.. (this points out a feature request maybe, labels dirs on Meta)

    For me either go with (1) drop the shortcut if it's not going to work as a shorcut, or (2) properly support the use-case when you have a bunch of explicitly defined fields on a ModelSerializer

  14. lovelydinosaur commented on Mar 31, 2017

    @lovelydinosaur
    Member

    This ain't fixed yet

    It's not that it "ain't fixed", it's that it's not something I'd want to support.

    If there's a field explicitly declared on the serializer, then that's what it'll use. You don't need additional shortcuts if you're explicitly declaring it.

    If it's the case that you want a subclass of that serializer where you modify a field to be read only then add the field explicitly on the subclass and mark it read only. Job done.

  15. 17 remaining items

  16. Jorl17 commented on Oct 28, 2021

    @Jorl17

    I have created PR #8228 to help with this.

  17. 381e35 commented on Aug 7, 2022

    @381e35

    Here in 2022, issue still exists.

  18. samuelchen commented on Dec 20, 2022

    @samuelchen

    same here, even the field is not explicitly declared.

    e.g. I can update fields in read_only_fields, such as username, is_superuser and etc.

    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = UserModel
            fields = ['id', 'username', 'first_name', 'last_name', 'password',
                      'is_active', 'is_superuser', 'is_staff', 'date_joined',
                      'groups', 'user_permissions']
            read_only_fields = ['username' 'is_superuser', 'is_staff', 'groups',
                                'user_permissions', 'date_joined']
            depth = 1
            extra_kwargs = {'password': {'write_only': True}}
    class UserViewSet(mixins.ListModelMixin, mixins.CreateModelMixin,
                      mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                      mixins.DestroyModelMixin,
                      viewsets.GenericViewSet):
        queryset = UserModel.objects.all()
        serializer_class = UserSerializer
        # permission_classes = [IsAuthenticated]
    
        def get_queryset(self):
            if self.request.user.is_staff:
                return super().get_queryset()
            else:
                return super().get_queryset().filter(id=self.request.user.id)
    
        def get_permissions(self):
            if self.action in ['create']:
                permission_classes = [IsAdminUser]
                return [perm() for perm in permission_classes]
            
            # ['list', 'retrieve', 'update', 'partial_udpate', 'destroy']
            return super().get_permissions()
  19. reopened this on Dec 21, 2022
  20. auvipy commented on Dec 21, 2022

    @auvipy
    Collaborator

    I have created PR #8228 to help with this.

    I have requested a change on the PR. please try to address that. @samuelchen can you also check the related PR and suggest any additional edge case/test case there as well?

  21. samuelchen commented on Dec 21, 2022

    @samuelchen

    I have created PR #8228 to help with this.

    I have requested a change on the PR. please try to address that. @samuelchen can you also check the related PR and suggest any additional edge case/test case there as well?

    I added the case to #8228 .

  22. changed the title [-]read_only_fields not working when specifying field explicitly[/-] [+]Document that explicitly declared fields will not have their attributes overridden by `read_only_fields` shortcut.[/+] on Mar 21, 2024
  23. stale commented on Oct 18, 2025

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  24. abidaliamanat9 commented on Aug 30, 2026

    @abidaliamanat9
    Contributor

    I've opened a PR that documents this: read_only_fields is ignored for fields declared explicitly on the serializer, so you need read_only=True on the field itself.

    #10028

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions