'Django REST framework - Adding Depth in Serializer gives Foreign Key Constraint Failed on POST data

I am having a model like this:

class KioskShelfMapping(models.Model):
    mapped_shelf_basket_name_reference = models.ForeignKey(ShelfBasketMapping, on_delete=models.CASCADE, default=1)
    mapped_shelf_name = models.CharField(max_length=15, null=False, blank=False, default="default")
    mapped_kiosk_name = models.CharField(max_length=15, blank=False, null=False, default="default")
    shelf_position = models.PositiveSmallIntegerField(null=False, blank=False, default=0)

and below is my Serializer:

class KioskShelfMappingSerializer(serializers.ModelSerializer):
    class Meta:
        model = KioskShelfMapping
        fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position']
        depth = 2

The issue I am facing is whenever I am adding the depth on POSTING some data to the model gives me

FOREIGN KEY constraint failed

But when I remove the depth field, I am able to POST the data to the model successfully. I tried searching for the same issue and found this and modified my serializer accordingly:

class KioskShelfMappingSerializer(serializers.ModelSerializer):

    class Meta:
        model = KioskShelfMapping
        fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position']
        depth = 2
    
    def __init__(self, *args, **kwargs):
        super(KioskShelfMappingSerializer, self).__init__(*args, **kwargs)
        request = self.context.get('request')
        if request and request.method =='POST':
            print('Method is POST')
            self.Meta.depth = 0
            print(self.Meta.depth)
        else:
            self.Meta.depth = 2

This doesn't seem to work. I still get the same error. Where am I going wrong? Thanks for you help in advance.



Solution 1:[1]

def __init__(self, *args, **kwargs):
    super(ProductSerializer, self).__init__(*args, **kwargs)
    request = self.context.get('request')
    if request and request.method == 'POST' or request.method == 'PUT' or request.method == 'PATCH':
        print('Method is POST')
        self.Meta.depth = 0
        print(self.Meta.depth)
    else:
        print(f"Method is - {request.method}")
        self.Meta.depth = 2

or

    def __init__(self, *args, **kwargs):
    super(ProductSerializer, self).__init__(*args, **kwargs)
    request = self.context.get('request')
    self.Meta.depth = 0
    if request and request.method == 'GET':
        self.Meta.depth = 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Memet Aktan