views.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from django.contrib.auth.models import Group
  2. from django.db.models import Sum
  3. from rest_framework import status
  4. from rest_framework.response import Response
  5. from rest_framework.views import APIView
  6. from rest_framework.viewsets import ModelViewSet
  7. from rolepermissions.roles import get_user_roles
  8. from basic.models import Menu, RouterMenu, GroupRouterMenu
  9. from basic.serializer import MenuSerializer, RouterMenuSerializer, GroupRouterMenuSerializer
  10. from payment.models import Payment
  11. class MenuView(ModelViewSet):
  12. queryset = Menu.objects.all()
  13. serializer_class = MenuSerializer
  14. pagination_class = None
  15. filter_fields = {'code': ['exact'], 'parent': ['exact']}
  16. class StatisticsView(APIView):
  17. def get(self, request):
  18. data = list(
  19. Payment.objects.values('payment_type').annotate(price_sum=Sum('index_price')).order_by('-price_sum'))
  20. return Response(data, status=status.HTTP_200_OK)
  21. class GroupRouterMenuView(APIView):
  22. queryset = Menu.objects.all()
  23. serializer_class = GroupRouterMenuSerializer
  24. pagination_class = None
  25. def get(self, request):
  26. user = request.user
  27. if user.is_superuser:
  28. return Response(RouterMenu.objects.all().values(), status=status.HTTP_200_OK)
  29. role = get_user_roles(user)
  30. # 根据当前用户的角色获取角色id
  31. roleArr = Group.objects.filter(name__in=[r.get_name() for r in role]).all().values('id')
  32. # 根据角色id查到所有相关的角色与菜单对应的记录
  33. menu = GroupRouterMenu.objects.filter(group_id__in=[arr['id'] for arr in roleArr]).all()
  34. # 生成菜单列表
  35. data = [RouterMenuSerializer(m.menu).data for m in menu]
  36. return Response(data, status=status.HTTP_200_OK)
  37. class RouterMenuView(ModelViewSet):
  38. queryset = Menu.objects.all()
  39. serializer_class = RouterMenuSerializer
  40. pagination_class = None