自关联 顾名思义 自己关联自己文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
下面这个例子将会讲到自管理(省市区 三级联动的例子)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
- 省的上一级(parant)为None
- 市的上一级(parant)为省
- 区的上一级(parant)为市
如果查到一地区的parant为None说明它是省一级地区,如果不为None就可以知道该地区是那个省那个市那个区的了文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
模型类:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
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='上级行政区划')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.htmlclass Meta:
db_table = 'area'
verbose_name= '行政区划'
verbose_name_plural = verbose_name文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
序列器:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
class AreaSer(serializers.ModelSerializer):文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
class Meta:
model = Area
fields = ('id','name')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.htmlclass SubSer(serializers.ModelSerializer):
# 外键 序列化
subs = AreaSer(many=True,read_only=True)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.htmlclass Meta:
model = Area
fields =('id','name','subs')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
视图:只进行查询操作 所以选用ReadOnlyModelViewSet视图集文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
class AreaView(ReadOnlyModelViewSet):
# 重写获取查询集以及序列化器类
def get_queryset(self):
if self.action == 'list':
return models.Area.objects.filter(parent=None)
else:
return models.Area.objects.all()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.htmldef get_serializer_class(self):
if self.action == 'list':
return ser.AreaSer
else:
return ser.SubSer文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
路由:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
router = DefaultRouter()
router.register(r'areas', views.AreaView, base_name='areas')
urlpatterns += router.urls文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
测试:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
详情页文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html
————————————————
版权声明:本文为CSDN博主「happy_leizi」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/happy_leizi/article/details/88662952文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28175.html