Skip to content
Advertisement

Nested Serializer save post foreign key in django

In my project, the relationship between Product and Group is ManytoOne.

When I tried to post a new product, it cannot work.

I’m sure there are more issues with this code and I will appreciate a detailed answer, because I am new to Django and Python. Thank you in advance.

models.py

class Group(models.Model):
    productType = models.CharField(max_length=100)
    intervalTime = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False)

    def __str__(self):
        return self.productType
    

class Product(models.Model):
    productName = models.CharField(max_length=255)
    color = models.CharField(max_length=255)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False)

    def __str__(self):
        return self.productName

serializers.py

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id','productType','intervalTime')


class ProductSerializer(serializers.ModelSerializer):
    group = GroupSerializer(many=False)
    class Meta:
        model = Product
        fields = ('id','productName','color','group')

    def create(self, validated_data):
        group = validated_data.pop('group')
        product = Product.objects.create(**validated_data)
        for group_instance in group:
            Group.objects.create(**group_instance, product=product)
        return product 

views.py

@api_view(['POST'])
def createProduct(request):
    serializer = ProductSerializer(data=request.data)

    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

Advertisement

Answer

First change serializers.py:

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id','productType','intervalTime')


class ProductInfoSerializer(serializers.ModelSerializer):
    group = GroupSerializer(read_only=True)

    class Meta:
        model = Product
        fields = ('id','productName','color','group')


class ProductCreationSerializer(serializers.ModelSerializer):
    group = serializers.SlugRelatedField(slug_field='productType', queryset=Group.objects.all())

    class Meta:
        model = Product
        fields = ('productName','color','group')

Then change views.py:

from rest_framework import status

@api_view(['POST'])
def createProduct(request):
    serializer = ProductCreationSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    instance = serializer.save()
    return Response(status=status.HTTP_200_OK, data=ProductInfoSerializer(instance=instance).data)
Advertisement