Home > Back-end >  saving foreign key relations using DRF
saving foreign key relations using DRF

Time:11-09

I am trying to save foreign key relations using serializer , I don't know where I am wrong here i have spent hours thinking about his now , don't seem to understand where the error lies, create method is not working and it's not saving any data either

 class Catalogs(viewsets.ModelViewSet):
    queryset = Catalog.objects.all()
    serializer_class  = CatalogSerializer


    def create(self, request, *args, **kwargs):
        if request.data:
            serialized_data = self.get_serializer(
               data = request.data
            )

serializer

class CatalogSerializer(serializers.ModelSerializer):
    catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True)
    
    def create(self,validated_data):
        client_id = validated_data.pop('id')
        catalog_obj = Catalog.objects.create(
                client = User.objects.get(id=client_id),
            )
        
        CatalogProducts.objects.create(
            catalog = catalog_obj,
            **validated_data
        )
        return catalog_obj

    
    class Meta:
        model = Catalog
        fields = ['created_by','client','catalog_products','created_datetime','is_active']


    

CodePudding user response:

It's hard to tell what is wrong without seeing the error message.

But here are the thing that you need to change:

serialized_data is not the actual serialized data but the serializer instance. You need to call save() method of the serializer to save the instance and data() method to get the serialized data.

serializer_cls = self.get_serializer()
serializer = serializer_cls(data=request.data)
serializer.is_valid(raise_exception=True)

catalog_instance = serializer.save()
catalog_serialized_data = serializer.data()
  • Related