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
 }
]

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

相关推荐