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}}
We set the model to Photo and add the 'image' field. It's going to be more efficiently manage uploading data.
Top comments (0)