Django 序列化含有外键的数据

发现问题

使用Django 自带的serialize可以方便的序列化数据库中的数据,但是不能处理外键和多对多关系。在dj自带的serialize序列化的数据中如果有外键的话,会自动使用主键进行序列化,不方便前端进行渲染。

解决方案

解决方案1

修改models,将需要显示的字段设置为自然键即可显示。但是这样不方便传送外键的全部属性。

# models.py
def __str__(self):
    return self.txt

def natural_key(self):
    return self.id, self.__str__()
# views.py
data_solved = table_obj.objects.filter(**filter_condition)
response['data'] = json.loads(serializers.serialize('json', data_solved, use_natural_foreign_keys=True))

解决方案2

使用djangorestfarmframeword进行序列化。可以任意指定显示的字段

# serializer.py
from rest_framework import serializers
from .models import *


class PaperSerialize(serializers.ModelSerializer):
    class Meta:
        model = Paper
        fields = "__all__"


class TypeSerialize(serializers.ModelSerializer):
    class Meta:
        model = QuestionTypes
        fields = "__all__"  


class DifficultySerialize(serializers.ModelSerializer):
    class Meta:
        model = QuestionDifficulty
        fields = "__all__"


class KnowledgePointSerialize(serializers.ModelSerializer):
    class Meta:
        model = KnowledgePoint
        fields = "__all__"


class QuestionSerialize(serializers.ModelSerializer):
    knowledge_point = KnowledgePointSerialize(many=True)
    type = TypeSerialize
    difficulty = DifficultySerialize
    paper_name = PaperSerialize

    class Meta:
        model = Question
        fields = "__all__"

# views.py
# 设置many=True以使用QuerySet进行序列化
response['data'] = QuestionSerialize(Question.objects.filter(condion), many=True)

你可能感兴趣的:(django,序列化)