Home > Software engineering >  How to properly extend Create method in Model Serializer?
How to properly extend Create method in Model Serializer?

Time:10-29

So I wanted to add some information for model fields during saving the object. For example I wanna upload an image and it should be the only required field, so i wanted the rest of the fields (e.g. width, height, name and so on) to be filled during saving the instance.

I take it that create method in serializer is where the instance of model is being saved. But it seems to me that copy and past all code from the initial create method seems kinda excesive.

I don't want to simply override the method because in that case there's a high chance I lose some validations or something.

So are there any ways to extend create method using super() for example?

So here is my model:

class ImageUpload(models.Model):

    name = models.CharField(max_length=150, default='test')
    url = models.URLField(default='None')
    picture = models.ImageField(upload_to='images/')
    width = models.IntegerField()
    height = models.IntegerField()
    parent_picture = models.IntegerField(default=0)

and here's my view:

class UploadImageView(generics.CreateAPIView):
    serializer_class = ImageUploadSerializer

And here's my sereializer:

class ImageUploadSerializer(serializers.ModelSerializer):
    class Meta:
        model = ImageUpload
        fields = '__all__'

    def create(self, validated_data):
        name = 'SomeName'
        width = 'Width of the uploaded image'
        height = 'Height of the uploaded image'
        super().create(validated_data)
        instance = ImageUpload.objects.create(**validated_data, name=name, width=width, height= height)
        return instance

Thank you beforehand!

CodePudding user response:

On your serializer you can do this and call default create :

class ImageUploadSerializer(serializers.ModelSerializer):
    class Meta:
        model = ImageUpload
        fields = '__all__'

    def create(self, validated_data):
        validated_data['name'] = 'SomeName'
        validated_data['width']= 120
        validated_data['height']= 120
        return super().create(validated_data)
  • Related