0

I have the following model:

class Collection(models.Model):
    ...
    relationships = models.ManyToManyField('relationships.Relationships', related_name='collections', blank=True)
    ...

I also have the following serializer:

class CollectionSerializer(serializers.ModelSerializer):
    relationships = RelationshipSerializer(many=True)

    class Meta:
        model = Collection
        fields = [
            ...
            'relationships',
            ...
        ]
        read_only_fields = [
            ...
        ]

    def create(self, validated_data):
        relationships = validated_data.pop('relationships')

        # Then we need to create an instance of the Collection object from the validated data:
        collection = Collection.objects.create(**validated_data)

        for relationship in relationships:
            relationship = Relationships.objects.get(uuid=relationship['uuid'])
            collection.relationships.add(relationship.id)

        return collection

A sample body I am posting to the endpoint where this serializer is called is:

{
    "relationships": [
        {
            "name": [
                "Relationship with this Name already exists."
            ]
        },
        {
            "name": [
                "Relationship with this Name already exists."
            ]
        }
    ]
}

Even when I set the relationships field to read only it throws this error?

What have I done wrong?

Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76
  • I think you've missed pasting/adding something to your code – JPG Mar 05 '21 at 14:53
  • @JPG Good spot - don't know what happened there. Added the missing pieces. – Micheal J. Roberts Mar 05 '21 at 14:58
  • I think you're using the http post method, if so, DRF thinks that you are trying to ***create*** instance and thus the validation error – JPG Mar 05 '21 at 15:00
  • Hi @JPG - I'm posting the collection obj (with the relationships Array nested) to the collections endpoint though ... this is what they advise doing on the DRF site and something I use elsewhere without such validation error being thrown. – Micheal J. Roberts Mar 05 '21 at 15:04
  • related, maybe; [Unique validation on nested serializer on Django Rest Framework](https://stackoverflow.com/questions/38438167/unique-validation-on-nested-serializer-on-django-rest-framework) – JPG Mar 05 '21 at 15:14

0 Answers0