forked from erp-dev/erp
54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
"""
|
||
Products API Views
|
||
快速产品查询接口,用于前端下拉框和自动完成
|
||
"""
|
||
from rest_framework import viewsets, status
|
||
from rest_framework.response import Response
|
||
from rest_framework.permissions import IsAuthenticated
|
||
from rest_framework.pagination import LimitOffsetPagination
|
||
from django_filters.rest_framework import DjangoFilterBackend
|
||
from rest_framework import filters
|
||
from basic_info.models import Product
|
||
|
||
|
||
class ProductQuickViewSet(viewsets.GenericViewSet):
|
||
"""
|
||
产品快速查询接口
|
||
|
||
专门为前端下拉框和自动完成提供的轻量级接口
|
||
只返回 id 和 name,支持分页和模糊搜索
|
||
"""
|
||
queryset = Product.objects.all()
|
||
permission_classes = [IsAuthenticated]
|
||
pagination_class = LimitOffsetPagination
|
||
filter_backends = [DjangoFilterBackend, filters.SearchFilter]
|
||
search_fields = ['name']
|
||
|
||
def list(self, request, *args, **kwargs):
|
||
"""
|
||
获取产品列表(仅 id 和 name)
|
||
|
||
查询参数:
|
||
- limit: 返回结果数量,默认无限制
|
||
- offset: 偏移量,默认0
|
||
- search: 按名称模糊搜索
|
||
|
||
示例:
|
||
- GET /api/v1/products/quick/?limit=10&offset=0
|
||
- GET /api/v1/products/quick/?search=布料
|
||
"""
|
||
queryset = self.filter_queryset(self.get_queryset())
|
||
|
||
# 分页
|
||
page = self.paginate_queryset(queryset)
|
||
if page is not None:
|
||
data = [{'id': p.id, 'name': p.name} for p in page]
|
||
return self.get_paginated_response(data)
|
||
|
||
# 不分页(如果没有 limit 参数)
|
||
data = [{'id': p.id, 'name': p.name} for p in queryset]
|
||
return Response({
|
||
'count': len(data),
|
||
'results': data
|
||
})
|