Posting empty foreign key field when creating parent object

Hi,

I have the following models (please not these are simplified from a much larger model structure where this relationship schema does indeed make sense):

My models.py:

class Supplier(models.Model):
	name = models.CharField(max_length=500)
	address = models.CharField(max_length=500, blank=True)

class NationalIndustry(models.Model):
	name = models.CharField(max_length=500)
	code = models.CharField(max_length=500)

	def __str__(self):
		return f"{self.name} - {self.code}"

# This maps an industry to a supplier.
class SupplierIndustry(models.Model):
	supplier = models.ForeignKey(Supplier, related_name='industries', on_delete=models.CASCADE, blank=True)
	industry = models.ForeignKey(NationalIndustry, related_name='suppliers', on_delete=models.SET_NULL, null=True, blank=True)
	code = models.CharField(max_length=500)

My serializers.py:

class SupplierIndustrySerializer(serializers.ModelSerializer):
    class Meta:
        model = SupplierIndustry
        fields = ['industry', 'code']

class SupplierSerializer(serializers.ModelSerializer):
    industries = SupplierIndustrySerializer(many=True)

    class Meta:
        model = Supplier
        fields = ['id', 'name', 'address', 'contact_number', 'description', 'industries']

My supplier view (because I have a large dataset, I want to be able to post lists at a time):

class SupplierList(generics.ListCreateAPIView):
    queryset = Supplier.objects.all()
    serializer_class = SupplierSerializer
    pagination_class = SmallResultsSetPagination
    
    def create(self, request, *args, **kwargs):
        try:
            serializer = self.get_serializer(data=request.data, many=True)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        except Exception as e:
            print(e)
            return Response({}, status=status.HTTP_400_BAD_REQUEST)

Now the issue is, when I post to the supplier endpoint, I get the following issue:

{‘industries’: [ErrorDetail(string=‘This field is required.’, code=‘required’)

If I remove the industries field from the SupplierSerializer it all works fine, but if I include it as per the code above, it gives the error.

Can someone please explain how I can make the industries array such that it can be empty? Any guidance would be much appreciated!

I believe you’re running up against a common issue with DRF. Check out the docs on writable nested serializers.