django rest framework 外键序列化方法与问题总结

大城市里の小女人 提交于 2020-03-24 07:22:29

3 月,跳不动了?>>>

django rest framework 外键序列化方法与问题总结

当借口中需要出现一对多关系的时候,我们可以用rest_framwork的序列化功能来处理,代码如下.

# models.py
from django.db import models


class PersonGoals(models.Model):
    name = models.CharField(max_length=100, verbose_name="目标名称")
    desc = models.CharField(max_length=200, verbose_name="说明")
    status = models.IntegerField()

    class Meta:
        db_table = "person_goals"

    def __str__(self):
        return self.name


class KeyResult(models.Model):
    name = models.CharField(max_length=100, verbose_name="结果名称")
    desc = models.CharField(max_length=200, verbose_name="结果说明")
    status = models.IntegerField()
    person = models.ForeignKey(to=PersonGoals, on_delete=None, related_name="result")

    class Meta:
        db_table = "key_result"

    def __str__(self):
        return self.name

# serialize.py
from rest_framework import serializers
from apple.models import PersonGoals, KeyResult


class KeyResultSerialize(serializers.ModelSerializer):
    class Meta:
        model = KeyResult
        fields = "__all__"


class PersonSerialize(serializers.ModelSerializer):
    result = KeyResultSerialize(many=True)  # 这里的result是ForeignKey中的related_name

    class Meta:
        model = PersonGoals
        fields = "__all__"

# views.py

from rest_framework.response import Response
from rest_framework.views import APIView

from apple.serializer import PersonSerialize, KeyResultSerialize
from apple.models import PersonGoals, KeyResult


class PersonView(APIView):
    def get(self, request):
        serialize = PersonSerialize(PersonGoals.objects.all(), many=True)
        return Response(serialize.data)


class KeyResultView(APIView):
    def get(self, request):
        serialize = KeyResultSerialize(KeyResult.objects.all(), many=True)
        return Response(serialize.data)

# urls.py
from django.urls import path
from apple import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    path("person/", views.PersonView.as_view(), name="person"),
    path("result/", views.KeyResultView.as_view(), name="result")
]

urlpatterns = format_suffix_patterns(urlpatterns)

效果如下

访问接口 http://127.0.0.1:8000/person/

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 1,
        "result": [
            {
                "id": 1,
                "name": "学习多层接口处理方法",
                "desc": "使用1对多时的处理方法",
                "status": 1,
                "person": 1
            },
            {
                "id": 2,
                "name": "学习多层接口处理方法二",
                "desc": "不使用1对多处理",
                "status": 1,
                "person": 1
            }
        ],
        "name": "rest_framwork深度学习",
        "desc": "深入学习rest_framwork的api使用",
        "status": 1
    }
]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!