DEV Community

Gahyun Son
Gahyun Son

Posted on

Seperate serializers

We don't need to define all things in a single serializer.
Let's create separate serializers! Then, why we creating a separate serializers is better?
It is because when we upload data, we don't need any other values that aren't relevant to the upload process.
We separate APIs and the best practice is to only upload one type of data to an API.

Here is examples.
I'm creating a 'Photos' Model with features such as id, title, description and date.
Now, I want to add an image feature.

class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields = ['id', 'title', 'description', 'date']

class PhotoImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields = ['id', 'image']
        read_only_fields = ['id']
        extra_kwargs = {'image': {'required': True}}
Enter fullscreen mode Exit fullscreen mode

We set the model to Photo and add the 'image' field. It's going to be more efficiently manage uploading data.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay