我用neo4j使用django休息。对于我的项目,当创建节点时,我将获得当前节点将与它们相关的节点的id列表。为了表示,我将表示包含连接到该节点的节点数据的dicts列表。但由于串行器是字符串列表,dicts将转换为字符串。
我的问题不在于neo4j。我要求在django rest中使用不同的数据类型序列化来读取和写入相同的字段。
这是我的代码:
parser.error('your own message')
我尝试了read_only,write_only,但这对我没有帮助。
输入示例: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
输出示例:['123456', '654321']
但我目前的输出是这样的:[{some data of node 123456},{some data of node 654321}]
修改
回答neverwalkaloner回答的基础:
['{some data of node 123456}', '{some data of node 654321}']
答案 0 :(得分:3)
您可以像这样使用自定义问题的序列化程序:
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']
语法访问它。