我将 django rest 与 neo4j 一起使用。对于我的项目,在创建节点时,我将获得当前节点与其相关的节点的 id 列表。为了表示,我将表示包含连接到该节点的节点数据的字典列表。但是由于序列化程序是字符串列表,dicts 将转换为字符串。
我的问题不是关于 neo4j。我在 django rest 中要求一种方法来为同一字段的读写进行不同的数据类型序列化。
这是我的代码:
class ScreenSerializer(serializers.Serializer):
questions = serializers.ListSerializer(child=serializers.CharField())
def create(self, validated_data):
questions = validated_data.pop('questions')
screen = Screen(**validated_data).save()
for question_uid in questions:
# connect relation in neo4j between screen and questions
screen.save()
return screen
def to_representation(self, obj):
obj.questions = # List of dicts that contain every connected node data
obj = super().to_representation(obj)
return obj
我尝试过 read_only、write_only 但这并没有帮助我。
输入示例:
['123456', '654321']
输出示例:
[{some data of node 123456},{some data of node 654321}]
但我目前的输出是这样的:
['{some data of node 123456}', '{some data of node 654321}']
编辑:
neverwalkaloner 答案的基础答案:
def to_representation(self, obj):
obj.questions = # List of dicts that contain every connected node data
self.fields['questions'] = serializers.ListSerializer(child=serializers.DictField())
obj = super().to_representation(obj)
return obj
最佳答案
您可以像这样使用自定义问题的序列化程序:
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = models.Question
fields = ['field1', 'field2']
class ScreenSerializer(serializers.Serializer):
def create(self, validated_data):
questions = validated_data.pop('questions')
screen = Screen(**validated_data).save()
for question_uid in questions:
# connect relation in neo4j between screen and questions
screen.save()
return screen
def to_representation(self, obj):
self.fields['questions'] = QuestionSerializer(many=True)
return super().to_representation(obj)
内注
to_representation
您应该覆盖序列化程序的字段问题的方法。您可以通过 self.fields['questions']
访问它句法。
关于Django rest 序列化具有不同读写数据类型的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559326/