4

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Arg, so annoying that I didn't spot this. I had made it read_only as it should not be updated, but needs to be set at creation time. Do you know if there is a way to handle this type of scenario, or would I need to cater for it specifically?
Overwrite get_serializer() in the view and there test the method - if it's create then remove the field from the read-only fields (_meta class). Or, perhaps cleaner, overwrite get_serializer_class and return a different serializer when creating objects then when updating them.
@nicja yeah just do it manually. Remove the read_only arg and add required=False then make sure the serializer doesn't receive the sku during updates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.