djangodjango-modelsdjango-rest-frameworkdjango-viewsmodel-view

insert nested relationships in DB django


Need help , i am trying to push nested relations inside DB don't know where I am going wrong in this, is there something wrong with validated_data , which is a list of dict here , thanks in advance

class CatalogSerializer(serializers.ModelSerializer):
    catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True)
    
    
    class Meta:
        model = Catalog
        fields = ['created_by','client','catalog_products','created_datetime','is_active']


    
    def create(self,validate_data):
        client_id = validate_data.pop('id')
        client = User.objects.get(id=client_id),
        catalog_obj = Catalog.objects.create(
            client = client,
            created_by = self.context['user'],
            is_active =True,
        )
      
        for pricelist_ins in validate_data:
            CatalogProducts.objects.create(
                catalog = catalog_obj,**pricelist_ins)

        return catalog_obj

Basic Viewset

class CatalogViewset(viewsets.ModelViewSet):
    queryset = Catalog.objects.all()
    serializer_class  = CatalogSerializer
    permission_classes = []
    authentication_classes = []

    def create(self, request, *args, **kwargs):
        if request.data:
            try:
               
                serialized_data = self.get_serializer(data = request.data)
                if serialized_data.is_valid(raise_exception=True):
                    serialized_data.save()
                    return Response(serialized_data.data,status=200)
            except Exception as e:
                return Response({'error':str(e)},status=400)
        return Response({'status':'invalid request'},status=400)

the error I am getting in Postman

{
    "error": "{'catalog_products': [ErrorDetail(string='This field is required.', code='required')]}"
}

data i am posting

{

    "id":"2",
    "pricing_list":[
        {
        "from_quantity":"101",
        "to_quantiy":"34",
        "price":"1000"
        },
        {
        "from_quantity":"10",
        "to_quantiy":"501",
        "price":"2000"
        }
    ]
}

Solution

  • You have catelogue_products in the fields, it is by default required. But you are not posting any catelogue_products. You need to post data based on the fields of the serializer. validated data will not contain any other data, but valid data that was set in serializer.

    To make it optional you may try to add required=False in the serialzier like this:

    class CatalogSerializer(serializers.ModelSerializer):
        catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True, required=False)
        
        
        class Meta:
            model = Catalog
            fields = ['created_by','client','catalog_products','created_datetime','is_active']