I have this issue at the moment with DRF.
I’m recieving extra fields that the model is not using. But those values will define the fields within the model.
JavaScript
x
7
1
{
2
"file_name": "test",
3
"file_type": "jpg",
4
"file": basex64 file,
5
"url_img": null
6
}
7
And i got this model
JavaScript
1
5
1
class imageModel(models.Model):
2
id = models.AutoField(primary_key=True)
3
url_img = models.textField(null=False)
4
5
All I need is to parse file_name and file_type to upload img to create a url_img and upload it on cloud. Is there a way to do this via DRF?
Advertisement
Answer
The DRF way of doing this is, explicitly define your extra fields in the serializer class.
JavaScript
1
8
1
class ImageModelSerializer(serializers.ModelSerializer):
2
file_name = serializers.CharField(write_only=True)
3
file_type = serializers.CharField(write_only=True)
4
file = serializers.CharField(write_only=True)
5
6
class Meta:
7
model = ImageModel
8
fields = "__all__"
Here, I have used serializers.CharField
–(DRF Doc) since all of those data are strings (if not, choose serializer fields accordingly).
Also, setting write_only=True
–(DRF Doc) will help us to omit those fields from the response.