Django rest 序列化具有不同读写数据类型的字段

标签 django python-3.x neo4j django-rest-framework

我将 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/

相关文章:

Django prefetch_related 与 m2m 通过关系

javascript - Django : provide dynamically generated data as attachment on button press

python-3.x - 在Python中撤消 "import math"?

neo4j - 多标签节点的最优Neo4j索引策略

python - 批量插入 neo4j - 最佳选择?

mysql - neo4j 示例 - 图与关系概念

django - 高负载时具有最大请求限制 block 的 Gunicorn

python - 在项目和应用程序之间配置 Django url

python - Qt.ScrollBarAsNeeded 在实际需要时不显示滚动条

python - 如何创建除一组给定值之外的随机序列