2

I realize the title sounds silly but I want to be able to change the references to the Group objects for my User instances. But I do not want them to be able to create new groups or edit existing groups. I think what I want is a read only nested field. However, if I set it to read_only=True I do not get the data in my serializers validated data. If I set it to read_only=False then it tries to create a new Group instead of just changing the references.

class GroupSerializer(serializers.ModelSerializer):
    permissions = PermissionSerializer(many=True)

    class Meta:
        model = Group
        fields = (
            'pk',
            'name',
            'permissions',
        )

class UserSerializer(serializers.ModelSerializer):
    groups = GroupSerializer(many=True)
    ....

    class Meta:
        model = User
        exclude = (
            ....
        )

    def update(self, instance, validated_data):
        print(validated_data)
        return instance

    def validate_groups(self, value):
        print("validating groups")
        ....
        return value

With read_only=True nothing happens at all. I get the user back on my PATCH request but the user is exactly the same. With read_only=False I get a validation error returned to me {'groups': [{'name': ['group with this name already exists.']}]}

I have also tried overriding the create and update method on the GroupSerializer but with no change.

At most, I want the GroupSerializer just to validate that the group from the data exists.

Jared Mackey
  • 3,998
  • 4
  • 31
  • 50
  • This is the same as http://stackoverflow.com/questions/38438167/unique-validation-on-nested-serializer-on-django-rest-framework/ – Linovia Aug 31 '16 at 09:21

2 Answers2

1

Really late answer, but I stumbled upon this in another thread here on StackOverflow (unfortunately I can't find it now), and they referred to the following discussion.

The solution I used was to create two serializers - one for reading and another one for writing - and two respective ViewSets including the correct Mixins. So I could list the nested Foreign Keys when using a GET method and only POST using the identifier for the existing Model of the FK relation. I used the depth attribute. I hope that relates to this problem.

vamcs
  • 345
  • 3
  • 12
0

The best solution I have found was to use the PrimaryKeyRelatedField and that provides a read only interface where I can select items that already exists and associate them to the object.

Sadly, there is one downside which is that now when viewing those objects in a GET type view the details of the related object are not shown but rather just the PK. I will figure out a way around this soon, maybe multi-serializer viewsets will do the trick.

Here are the docs

Jared Mackey
  • 3,998
  • 4
  • 31
  • 50