django自關聯省市區模型建立

2021-09-10 14:18:02 字數 1818 閱讀 3385

class area(models.model):

'''行政區域'''

name = models.charfield(max_length=20,verbose_name='名稱')

parent = models.foreignkey('self',on_delete=models.set_null,related_name='subs',null=true,blank=true,verbose_name='上一級行政區')

class meta:

db_table = 'tb_areas'

verbose_name = '行政區劃'

verbose_name_plural = '行政區劃'

def __str__(self):

return self.name

新建序列化器:

from rest_framework import serializers

from .models import area

class areaserializer(serializers.modelserializer):

"""行政區劃資訊序列化器

"""class meta:

model = area

fields = ('id', 'name')

class subareaserializer(serializers.modelserializer):

"""子行政區劃資訊序列化器

"""subs = areaserializer(many=true, read_only=true)

class meta:

model = area

fields = ('id', 'name', 'subs')

檢視:

from django.shortcuts import render

from rest_framework.viewsets import readonlymodelviewset

from .models import area

from .serializers import areaserializer, subareaserializer

# create your views here.

class areasviewset(readonlymodelviewset):

"""行政區劃資訊

"""pagination_class = none # 區劃資訊不分頁

def get_queryset(self):

"""提供資料集

"""if self.action == 'list':

return area.objects.filter(parent=none)

else:

return area.objects.all()

def get_serializer_class(self):

"""提供序列化器

"""if self.action == 'list':

return areaserializer

else:

return subareaserializer

路由:

router = defaultrouter()

router.register(r'areas', views.areasviewset, base_name='areas')

urlpatterns =

urlpatterns += router.urls

全國省市區資料SQL 省市區

drop table if exists provinces create table provinces id int 11 not null auto increment,provinceid varchar 20 not null,province varchar 50 not null,pr...

省市區陣列

先找到檔案對應的路徑 nsstring path users dlios desktop oc5 省市區陣列 oc5 省市區陣列 area.txt 通過路徑產生字串,內容就是txt文字裡的內容 nsstring str nsstring stringwithcontentsoffile path e...

OC 省市區陣列

省市區陣列 先找到檔案對應的路徑 nsstring path users dlios desktop 筆記 oc筆記 oc5 陣列省市區 oc5 陣列省市區 area.txt 通過路徑產生字串,內容就是txt文字的內容 nsstring str nsstring stringwithcontents...