get() 返回了多个产品——它返回了 2 个 Django Rest Framework
get() returned more than one Product -- it returned 2 Django Rest Framework
DRF 返回这个:get() 返回了不止一个产品——它返回了 2 个!,当我试图通过 PK
从我的数据库中获取对象时
序列化器
class ProductSerializer(serializers.ModelSerializer):
# cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True)
class Meta:
model = Product
fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo')
观看次数
class CategoryProductView(APIView):
def get(self, request, pk):
product = Product.objects.get(cat_id=pk)
serializer = ProductSerializer(product)
return Response(serializer.data)
网址
path('api/categorylist/<int:pk>', CategoryProductView.as_view())
如果要序列化属于某个类别的某个主键的所有项目,您过滤并序列化 many=True
个项目,因此:
class CategoryProductView(APIView):
def get(self, request, pk):
products = Product.objects.<strong>filter(</strong>cat_id=pk<strong>)</strong>
serializer = ProductSerializer(products<strong>, many=True</strong>)
return Response(serializer.data)
DRF 返回这个:get() 返回了不止一个产品——它返回了 2 个!,当我试图通过 PK
从我的数据库中获取对象时序列化器
class ProductSerializer(serializers.ModelSerializer):
# cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True)
class Meta:
model = Product
fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo')
观看次数
class CategoryProductView(APIView):
def get(self, request, pk):
product = Product.objects.get(cat_id=pk)
serializer = ProductSerializer(product)
return Response(serializer.data)
网址
path('api/categorylist/<int:pk>', CategoryProductView.as_view())
如果要序列化属于某个类别的某个主键的所有项目,您过滤并序列化 many=True
个项目,因此:
class CategoryProductView(APIView):
def get(self, request, pk):
products = Product.objects.<strong>filter(</strong>cat_id=pk<strong>)</strong>
serializer = ProductSerializer(products<strong>, many=True</strong>)
return Response(serializer.data)