Answer a question

I am looking for a way to properly ovverride the default .create() method of a ModelSerializer serializer in Django Rest Framework for dealing with an extra parameter.

In my original Django model I have just overridden the default.save() method for managing an extra param. Now .save() can be called also in this way: .save(extra = 'foo').

I have to create a ModelSerializer mapping on that original Django model:

from OriginalModels.models import OriginalModel
from rest_framework import serializers

class OriginalModelSerializer(serializers.ModelSerializer):

    # model fields
    class Meta:
        model = OriginalModel

But in this way I can't pass the extra param to the model .save() method.

How can I properly override the .create() method of my OriginalModelSerializer class to take (eventually) this extra param into account?

Answers

Hmm. this might not be the perfect answer given I don't know how you want to pass this "extra" in (ie. is it an extra field in a form normally, etc)

What you'd probably want to do is just represent foo as a field on the serializer. Then it will be present in validated_data in create, then you can make create do something like the following

def create(self, validated_data):
    obj = OriginalModel.objects.create(**validated_data)
    obj.save(foo=validated_data['foo'])
    return obj

You'd probably want to look at the default implementation of create for some of the other things it does though (like remove many-to-many relationships, etc.).

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐