省市区三级联动接口的实现(Django)

本文采用DRF即(djangorestframework)来实现接口的设计

首先效果图:
省市区三级联动接口的实现(Django)_第1张图片

1、数据库

省市区三级联动接口的实现(Django)_第2张图片

2、模型models.py

省市区三级联动接口的实现(Django)_第3张图片

3、序列化器serializers.py

from rest_framework import serializers

from api.models import District


# 基本的序列化器
class BaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = District
        fields = ('name',)


# 市和区的序列化器
class AreaSerializer(serializers.ModelSerializer):
    area = serializers.SerializerMethodField()

    @staticmethod
    def get_area(city):
        queryset = District.objects.filter(parent=city).only('name')
        return BaseSerializer(queryset, many=True).data

    class Meta:
        model = District
        fields = ('name', 'area')


# 省和市和区的序列化器
class DistrictSerializer(serializers.ModelSerializer):
    city = serializers.SerializerMethodField()

    @staticmethod
    def get_city(pro):
        queryset = District.objects.filter(parent=pro).only('name')
        return AreaSerializer(queryset, many=True).data

    class Meta:
        model = District
        fields = ('name', 'city')

4、视图views.py

pid为空的表示省份
省市区三级联动接口的实现(Django)_第4张图片

大功告成

你可能感兴趣的:(Python,Django)