python - DRF 将数据传递到相关字段
问题描述
我有一个序列化器和一个用于通用外键关系的相关字段,应该用于序列化content_object
哪个是一个ContentType
实例。我需要检查我在相关字段中序列化type
的Notification
对象,以正确知道哪些附加字段要序列化到那里的data
参数中。实现这一目标的最佳方法是什么?
class NotificationRelatedField(serializers.RelatedField):
def to_representation(self, value):
data = {}
# Need to check notification 'type' here
return data
class NotificationRetrieveSerializer(serializers.ModelSerializer):
content_object = NotificationRelatedField(read_only=True)
class Meta:
model = Notification
fields = [
'id',
'created_at',
'is_read',
'type',
'content_object',
]
解决方案
您需要重写序列化程序的to_representation
方法以使用实例调用字段的to_representation
方法Notification
,而不是使用字段的值。
示例:
class NotificationRetrieveSerializer(serializers.ModelSerializer):
content_object = NotificationRelatedField(read_only=True)
class Meta:
model = Notification
fields = [
'id',
'created_at',
'is_read',
'type',
'content_object',
]
# override to_representation method
def to_representation(self, instance):
# python3 for `super` call
result = super().to_representation(instance)
# python2 for `super` call
# result = super(
# NotificationRetrieveSerializer, self
# ).to_representatio(instance)
# here you call your field's `to_representation` with current instance
# as the argument rather than as the `value` of the field.
result['content_object'] = content_object_field.to_representation(instance)
return result
class NotificationRelatedField(serializers.RelatedField):
# here `value` is now the `Notification` instance
def to_representation(self, value):
data = {}
# get the type and this field's value
type = value.type
content_object = value.content_object
return data
推荐阅读
- .net - RepoDb 是否具有像实体框架一样的数据验证?
- android - 反应本机应用程序中缺少 Android 和 ios 文件夹
- excel - 如何使 AppSource 安装链接在 Mac 上工作?
- python - 将 GPU 与 opencv-python 一起使用
- vim - 我想知道:CocSearch /pattern/ -A
- react-native - 如何在 React Native 中使用 Material-UI 图标
- android - 如何在android上获得图像的精确焦距?
- angular - Typescript json引用变量但需要检查变量是否存在
- javascript - 使用正则表达式检查每个出现的特殊字符后跟空格
- python - 如何使用 zeep 发送 xml 请求?