Home > Net >  Add fields in Serializer dynamically
Add fields in Serializer dynamically

Time:02-10

I have a View in which I receive the request and it returns the serialized data

views.py

class AllotmentReportsView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        sfields = request.GET['sfields']           #I can get the fields in params 
        serializer = AllotReportSerializer(items, many=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

serializer.py

class AllotReportSerializer(serializers.ModelSerializer):

    send_from_warehouse = serializers.SlugRelatedField(read_only=True, slug_field='name')
    transport_by = serializers.SlugRelatedField(read_only=True, slug_field='name')
    sales_order = AllotSOSerializer(many=False)
    flows = AllotFlowsSerializer(many=True)

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )

Instead of defining the fields in serializer can I pass the fields dynamically from the view sfields and pass them to the serializer ?

CodePudding user response:

It is not necessary to describe fields in ModelSerializer class. Django will generate it automatically according model information:

class AllotReportSerializer(serializers.ModelSerializer):

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )

is enough

If you want to add fields that not exists in model, I guess it is possible with meta classes and setattr() function. But that is looking meaningless. Also you need to add logic how to dynamically set field type and parameters.

CodePudding user response:

You do not need to describe the fields in the ModelSerializer -

class AllotReportSerializer(serializers.ModelSerializer):

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )
    extra_kwargs = {
           "url": {
               "lookup_field": "slug",  
               "view_name": "api-your-model-name-detail",
            }

you can define extra kwargs if you want in the above way. This is enough.

If you want to add all the fields in your model, you can do this -

class Meta:
    model = Your model name
    fields = "__all__"

You can read more about it here - https://www.django-rest-framework.org/api-guide/serializers/

  • Related