Django Rest Framework error in nested create serializers

Viewed 251

I am trying to insert info into the db with nested serializers, but I have errors

  • Django 3.2
  • djangorestframework 3.12.4

dummy models

class Supplier(models.Model):
    name = models.CharField(max_length=250)


class SupplierContacts(models.Model):
    supplier = models.ForeignKey(
        'Supplier',
        related_name='contacts',
        on_delete=models.CASCADE
    )
    last_name = models.CharField(max_length=50)


class SupplierUsers(models.Model):
    supplier = models.ForeignKey(
        'Supplier',
        related_name='users',
        on_delete=models.CASCADE
    )
    last_name = models.CharField(max_length=50)
  

dummy serializers


class SupplierSerializer(serializers.ModelSerializer):
    users = SupplierUserSerializer() 
    contacts = SupplierContactsSerializer(many=True)

    class Meta:
        model = Supplier
        fields = [
            'name',
            'users',
            'contacts'
        ]

    def create(self, validated_data):
        users_data = validated_data.pop('users')
        contacts_data = validated_data.pop('contacts')

        supplier = Supplier.objects.create(**validated_data)
        SupplierUsers.objects.create(supplier=supplier, **users_data)

        for contact in contacts_data:
            SupplierContacts.objects.create(supplier=supplier, **contact)

        return supplier

In views custom create like this

class ViewSet(mixins.CreateModelMixin,
              viewsets.GenericViewSet):

    queryset = Supplier.objects.all()
    serializer_class = SupplierSerializer

    def create(self, request, *args, **kwargs):
        # import ipdb
        # ipdb.set_trace()
        serializer = SupplierSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()  # here works saved to db
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I am doing what it says in the documentation, but I have the following error.

AttributeError: Got AttributeError when attempting to get a value for field `last_name` on serializer `SupplierUserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance.
Original exception text was: 'RelatedManager' object has no attribute 'last_name'.

Data is saved, the problem is in deserializing => serializer.data

Any ideas?

0 Answers
Related