如何在DB模型中使用DRF自定义序列化程序字段 [英] How to use DRF Custom serializer field with DB model
问题描述
我正在使用具有二进制字段的关系数据库,那么如何使用DRF序列化程序保存字段值
I'm using relation database which is having Binary Field, So how can I use DRF serializer to save the field value
我已经参考了文档 https://www.django-rest-framework.org/api- guide / fields /#custom-fields
并理解其中的一部分并在下面创建,但是我不确定如何在序列化程序中使用它
I have referred the documentation https://www.django-rest-framework.org/api-guide/fields/#custom-fields and understood some of the part and created below, but I'm not sure how to use it in serializer
模型
class MyData(models.Model):
data = models.BinaryField()
自定义字段
class BinaryField(serializers.Field):
def to_representation(self, value):
return value.decode('utf-8')
def to_internal_value(self, value):
return value.encode('utf-8')
但是我应该如何在b中使用它低级序列化器
But how should I use this in my below serializer
class BlobDataSerializer (serializers.ModelSerializer):
class Meta:
model = MyData
fields = ('id', 'data')
因此基本上我试图将传入的数据存储在二进制字段中。预先感谢
So basically I'm trying to store incoming data in binary field. Thanks in advance
推荐答案
像这样:
class BlobDataSerializer (serializers.ModelSerializer):
class Meta:
model = MyData
fields = ('id', 'data')
data = BinaryField()
对于更可重用的解决方案,您还可以继承ModelSerializer并自定义 serializer_field_mapping
。
For a more reusable solution, you could also subclass ModelSerializer and customize the serializer_field_mapping
.
请参见 https://www.django-rest-framework.org/api-guide/serializers/#customizing-field-mappings
这篇关于如何在DB模型中使用DRF自定义序列化程序字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!