如何基于Django Rest Framework实现按条码查询指定产品的API
实现方案
1. 先确保产品模型的条码字段唯一
首先检查你的Product模型,给barcode字段加上唯一约束,避免多个产品共用同一条码导致查询异常:
# models.py from django.db import models class Product(models.Model): # 保留你原有其他字段 barcode = models.CharField(max_length=100, unique=True) # 添加unique=True约束 # 保留你原有其他字段
2. 修改视图类,实现两种查询方式
基础版(满足需求的最简实现)
修改views.py,配置lookup_field让详情接口支持条码路径,同时重写get_queryset支持查询参数过滤:
# views.py from rest_framework import viewsets from app1.models import Product from app1.serializers import ProductSerializer class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer # 指定详情接口用barcode作为查找字段,对应/api/products/[条码]路径 lookup_field = 'barcode' def get_queryset(self): queryset = super().get_queryset() # 处理?barcode=[条码]的查询参数 barcode = self.request.query_params.get('barcode') if barcode: queryset = queryset.filter(barcode=barcode) return queryset
此时效果:
/api/products/[条码]:返回匹配条码的单个产品JSON对象/api/products/?barcode=[条码]:返回包含匹配产品的JSON数组(即使只有一个产品)
优化版(让查询参数返回单个对象)
如果希望/api/products/?barcode=[条码]直接返回单个产品对象(和详情接口格式一致),重写list方法:
# views.py from rest_framework import viewsets from rest_framework.response import Response from django.core.exceptions import MultipleObjectsReturned from app1.models import Product from app1.serializers import ProductSerializer class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'barcode' def list(self, request, *args, **kwargs): barcode = request.query_params.get('barcode') if barcode: try: product = Product.objects.get(barcode=barcode) serializer = self.get_serializer(product) return Response(serializer.data) except Product.DoesNotExist: return Response({"error": "未找到匹配条码的产品"}, status=404) except MultipleObjectsReturned: return Response({"error": "存在多个匹配该条码的产品"}, status=400) # 无barcode参数时,返回所有产品列表 return super().list(request, *args, **kwargs)
3. 功能验证
启动服务后测试:
- 访问
/api/products/6901234567890(替换为实际存在的条码),应返回单个产品的JSON数据 - 访问
/api/products/?barcode=6901234567890,优化版会返回单个产品对象,基础版返回含单个产品的数组
内容的提问来源于stack exchange,提问作者prensj
相关产品推荐
相关产品推荐

