I have the following in a Django Rest Framework setup:
models.py:
class Sku(BaseModel):
sku_code = models.CharField(max_length=18, primary_key=True)
supplier_id = models.PositiveIntegerField(db_index=True)
soh = models.PositiveIntegerField(default=0)
reserved = models.PositiveIntegerField(default=0)
broken = models.PositiveIntegerField(default=0)
unallocated = models.PositiveIntegerField(default=0)
reorder = models.PositiveIntegerField(default=0)
class Reservation(BaseModel):
sku = models.ForeignKey(Sku, db_column='sku_code')
order_id = models.PositiveIntegerField(db_index=True)
serializers.py:
class SkuSerializer(serializers.ModelSerializer):
class Meta:
model = Sku
fields = (
'sku_code',
'supplier_id',
'soh',
'reserved',
'broken',
'unallocated',
'reorder',
'created_at',
'modified_at',
)
class ReservationSerializer(serializers.ModelSerializer):
sku = SkuSerializer(read_only=True)
class Meta:
model = Reservation
fields = (
'id',
'order_id',
'sku',
'created_at',
'modified_at'
)
views.py:
class ReservationList(mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Reservation.objects.all()
serializer_class = ReservationSerializer
def post(self, request, *args, **kwargs):
sku = get_object_or_404(Sku, sku_code=request.data['sku_code'])
request.data['sku'] = sku
return self.create(request, *args, **kwargs)
Now when I post to the url linked to ReservationList.post view above I get the error: IntegrityError: (1048, "Column 'sku_code' cannot be null").
It seems to be bypassing the serializers validation and failing on the database layer. For some reason it doesn't accept the SKU being passed in.
What am I doing wrong here? I have tried to follow the example at http://www.django-rest-framework.org/api-guide/relations/#nested-relationships but this seems to break down with the CreateModelMixin. I can't tell if there is something wrong with how my models or serializers are set up.
You've set the sku field to read only, that's why the serializer is ignoring it when you post.
From the relevant documentation
Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With