forked from erp-dev/erp
78 lines
2.4 KiB
Python
78 lines
2.4 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 和 image,支持分页和模糊搜索
|
||
|
||
性能优化:
|
||
- 使用 .only() 只查询需要的字段,避免 SELECT *
|
||
- 减少数据传输量
|
||
- 提升查询速度
|
||
"""
|
||
queryset = Product.objects.only('id', 'name', 'image') # 性能优化:只查询需要的字段
|
||
permission_classes = [IsAuthenticated]
|
||
pagination_class = LimitOffsetPagination
|
||
filter_backends = [DjangoFilterBackend, filters.SearchFilter]
|
||
search_fields = ['name']
|
||
|
||
def list(self, request, *args, **kwargs):
|
||
"""
|
||
获取产品列表(仅 id, name 和 image)
|
||
|
||
查询参数:
|
||
- limit: 返回结果数量,默认无限制
|
||
- offset: 偏移量,默认0
|
||
- search: 按名称模糊搜索
|
||
|
||
返回字段:
|
||
- id: 产品ID
|
||
- name: 产品名称
|
||
- image: 产品图片URL(可能为null)
|
||
|
||
示例:
|
||
- 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,
|
||
'image': p.image.url if p.image else None
|
||
}
|
||
for p in page
|
||
]
|
||
return self.get_paginated_response(data)
|
||
|
||
# 不分页(如果没有 limit 参数)
|
||
data = [
|
||
{
|
||
'id': p.id,
|
||
'name': p.name,
|
||
'image': p.image.url if p.image else None
|
||
}
|
||
for p in queryset
|
||
]
|
||
return Response({
|
||
'count': len(data),
|
||
'results': data
|
||
})
|