Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass parameters which are not associated with a serializer field in Django Rest Framework?

Tags:

rest

django

I have a form with fields which are not associated with a model. I assume to implement the equivalent using a REST API (django-rest-framework), I would have to pass those additional fields, which are not associated with a Serializer? How do I do that?

Let's say the additional field is number_of_pages. I use that for some calculation. How do I allow that to be passed in my REST call?

like image 557
nilanjan Avatar asked Oct 18 '22 09:10

nilanjan


1 Answers

if you are using ModelSerializer from DjangoRestFramework, just add a field.

by default only model fields are added, but nothing limits you to add more, the only thing that may be problematic (but I've not tested it) - you may have too many fields while creating or updating model - in such a case, you will need to remove those fields in create() and update() methods before calling save().

class MyModelSerializer(serializers.ModelSerializer):
    number_of_pages = fields.IntegerField()

    # this I'm not sure if needed
    def create(self, validated_data):
        validated_data.pop('number_of_pages')
        return super(MyModelSerializer, self).create(validated_data)

    def update(self,instance, validated_data):
        validated_data.pop('number_of_pages')
        return super(MyModelSerializer, self).update(instance, validated_data)
    # end

    class Meta:
        fields = ('mymodelfield_1', 'mymodelfield_2', 'number_of_pages')
        model = MyModel
like image 97
Jerzyk Avatar answered Oct 21 '22 02:10

Jerzyk