1
0
forked from erp-dev/erp
Files
erpnew/api_v1/views/products/views.py
2025-12-25 21:36:50 +08:00

78 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Products API Views
快速产品查询接口,用于前端下拉框和自动完成
"""
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from flower.viewsets import LimitedGenericViewSet
from basic_info.models import Product
class ProductQuickViewSet(LimitedGenericViewSet):
"""
产品快速查询接口
专门为前端下拉框和自动完成提供的轻量级接口
只返回 id, name 和 image支持分页和模糊搜索
性能优化:
- 使用 .only() 只查询需要的字段,避免 SELECT *
- 减少数据传输量
- 提升查询速度
"""
queryset = Product.objects.only('id', 'name', 'image') # 性能优化:只查询需要的字段
permission_classes = [IsAuthenticated]
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
})