01收货地址模型类和视图定义_哔哩哔哩_bilibili 本博客借鉴至大佬的视频学习笔记
地址信息的管理:增删改查的实现
# 序列化器配置
class AddrSerializer(serializers.ModelSerializer):
"""收货地址的模型序列化器"""
class Meta:
model = Addr
fields = '__all__'
# view 视图信息
class AddrView(GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.UpdateModelMixin):
"""收货地址管理视图"""
queryset = Addr.objects.all()
serializer_class = AddrSerializer
permission_classes = [IsAuthenticated,AddrPermissions]
# filterset_fields = ('user',)
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
# 通过请求过来的用户进行过滤
queryset = queryset.filter(user=request.user)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
# url 配置
# 添加地址和获取地址列表的路由
path('address/', AddrView.as_view({'post':'create','get':'list'}), name='address'),
# 删除和修改地址
path('address/<int:pk>/', AddrView.as_view({'delete':'destroy','put':'update'}), name='address'),
# 注册过滤器
'django_filters'
# 配置过滤器
REST_FRAMEWORK = {
# 过滤器信息配置
'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend',]
}
默认收货地址的设置
# 如上 AddrView视图中增加默认地址函数
def set_default_addr(self,request,*args,**kwargs):
"""设置默认收货地址"""
# 将获取的地址设置为默认
obj =self.get_object()
obj.is_default =True
obj.save()
# 将其他地址进行遍历为非默认
queryset = self.get_queryset().filter(user=request.user)
for item in queryset:
if item !=obj:
item.is_default =False
item.save()
return Response({'message':'设置成功'},status=status.HTTP_200_OK)
# url 文件配置
path('address/<int:pk>/default/', AddrView.as_view({'put': 'set_default_addr'}), name='address'),
云短信使用:网址云通信精选特惠
购买成功后进入控制台,搜索短信服务:阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台
点击当前的SDK信息,安装依赖
2024/02/23 更新ing....