我正在尝试通过URL中指定的PK值过滤我的APIListView。代码运行,但是我的 API 是空的,即使我知道它在我正在测试的 PK 上有数据。有什么想法吗?
Models.py
class Item(models.Model):
Description = models.CharField(max_length=20)
Price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.Description
Serializers.py
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('pk', 'Description', 'Price')
Views.py (API(
class SingleItemAPIView(generics.ListAPIView):
serializer_class = ItemSerializer
def get_queryset(self):
item = self.request.query_params.get('pk', None)
queryset = Item.objects.filter(pk=item)
return queryset
Urls.py
urlpatterns = [
path('<int:pk>/',SingleItemAPIView.as_view(), name='single_object_view')
]
DRF 输出
GET /api/1/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[]
网址参数可以在self.kwargs
中找到
class SingleItemAPIView(generics.ListAPIView):
serializer_class = ItemSerializer
def get_queryset(self):
item = self.kwargs['pk']
queryset = Item.objects.filter(pk=item)
return queryset