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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With