class RobotLogView(APIView):
"""机器人日志视图"""
def get(self, request):
robot_id = request.query_params.get('robot_id')
machine_id = request.query_params.get("machine_id")
if not robot_id:
queryset = Log.objects.all().order_by('-tar_time')
else:
# 查询集
queryset = Log.objects.filter(robot_id=robot_id).order_by('-tar_time')
if machine_id:
queryset = Log.objects.filter(robot__machine_id=machine_id).order_by("-tar_time")
# 分页
pg = MyPageNumberPagination()
page_logs = pg.paginate_queryset(queryset=queryset, request=request, view=self)
# 序列化
ser_logs = serializers.LogSerializer(instance=page_logs, many=True)
return pg.get_paginated_response(data=ser_logs.data)
class MyPageNumberPagination(PageNumberPagination):
page_size = 15 # 默认每页显示2条
page_query_param = 'page' # 查询关键字名称:第几页
page_size_query_param = 'page_size' # 查询关键字名称:每页多少条
class LogSerializer(serializers.ModelSerializer):
tar_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
created_at = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
machine_id = serializers.PrimaryKeyRelatedField(source='robot.machine_id', read_only=True)
robot_id = serializers.PrimaryKeyRelatedField(source='robot', read_only=True)
class Meta:
model = Log
fields = "__all__"