Rahul Sharma
Rahul Sharma

Reputation: 2495

Add fields in Serializer dynamically

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 ?

Upvotes: 0

Views: 379

Answers (2)

Innomight
Innomight

Reputation: 556

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/

Upvotes: 0

rzlvmp
rzlvmp

Reputation: 9452

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.

Upvotes: 1

Related Questions