Skip to content

ModelSerializer exclude won't work well when field duplicate declear in Serializer #5596

Closed
@jacky15

Description

@jacky15

Checklist

  • I have verified that that issue exists against the master branch of Django REST framework.
  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • This is not a usage question. (Those should be directed to the discussion group instead.)
  • This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • I have reduced the issue to the simplest possible case.
  • I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

Steps to reproduce

I found that when I use ModelSerializer, if I set a field in ModelSerializer which is duplicate in model. Then ModelSerializer 's exclude attribute won't work well. It still return the exclude fields.

I traced down the code, and found that it failed because ModelSerializer.get_field_names exclude fields by using list. Since I have set the field in the ModelSerializer, there are two fields name in the list returned by ModelSerializer.get_default_field_names.

django model I except to have

class Car(models.Model):
    name = models.CharField(max_length=128)
    username = models.CharField(max_length=128)

serializar I have

class VersionModelSerializer(serializers.ModelSerializer):
    username = fields.IntegerField(validators=my_validator)

    class Meta:
        model = models.Car
        exclude = ('username')

Expected behavior

Excepted to return data like

{
    "name": "car_name"
}

Actual behavior

but username exists in the response like

{
    "name": "car_name",
    "username": "username"
}

according to the reason I explain above, I think ModelSerializer.get_field_names should use set instead of list to exclude fields.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions