我想获取特定类别的图像,例如如果我发出获取请求 localhost/api/image/3/我得到第三类图像
models.py:
class Image(models.Model):
title = models.CharField(max_length = 100)
image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png')
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
description = models.TextField(max_length=1000)
def __str__(self):
return self.title
view.py:
class ImageView(generics.ListCreateAPIView):
authentication_classes = []
permission_classes = []
pagination_class = None
serializer_class = ImageSerializer
def get_queryset(self):
cat = self.request.query_params['category']
return Image.objects.all().filter(category = cat)
serializers.py:
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ('title','category','image')
接口输出:
[
{
"title": "aka",
"category": 5,
"image": "http://localhost:8000/media/home/tboss/Desktop/image/logo.png"
},
{
"title": "aka",
"category": 7,
"image": "http://localhost:8000/media/home/tboss/Desktop/image/DSC_9314.JPG"
},
{
"title": "test",
"category": 3,
"image": "http://localhost:8000/media/home/tboss/Desktop/image/Pillars_Outdoor_OR_RD_50003619_1280x640_DQMyGuR.jpg"
}
]
urls.py:
path('image/', views.ImageView.as_view(), name = 'category_image'),
注意:序列化程序引用的模型(事件图像(未在上述 models.py 中定义。这是故意的吗?对我来说,你应该参考Image
您可以使用如下内容重写查询集:
class ImageView(generics.ListCreateAPIView):
authentication_classes = []
permission_classes = []
pagination_class = None
serializer_class = ImageSerializer
def get_queryset(self):
"""
If query_param URL exists, return filtered queryset
Else, return entire Image queryset
"""
# assuming you need an integer, so I'm casting cat to an INT
if 'category' in self.request.query_params:
cat = int(self.request.query_params['category'])
return Image.objects.all().filter(category=cat)
return Image.objects.all()
urls.py
path('image', views.ImageView.as_view(), name = 'category_image'),
在类别=my_category中获取图像,网址如下:
localhost/api/image?category=my_category
注:注:我没有在 URL 末尾包含尾部斜杠,主要是为了美观,我在上面相应地更新了 urls.py。
这将返回与所选类别匹配的所有图像的列表。
另一种方法是在URL中使用关键字参数。
# ListAPIView returns a list of objects.
# If you just want to return a single object,
# use RetreiveAPIView
# If you want a read-writeable endpoint,
# Use ListCreateAPIView or RetrieveCreateAPIView
class MyImageView(generics.ListAPIView):
serializer_class = ImageSerializer
def get_object(self):
return Image.objects.get(id=self.kwargs["cat"])
在 URL 中,您可以将其配置为接受关键字参数,在下面的代码中,cat
.这在视图和 URL 中都引用。
注:注:此 URL 必须始终包含类别,以便除了可能开发的其他 URL 之外,您还可以使用它。
# if you are expecting an integer, use int:cat
# if you're expecting a string, use str:cat
# this will be determined by the primary key type
# of your related model. It does appear though that it is an INT.
path('image/<int:cat>', MyImageView.as_view()), name='cat_image'),
然后,您可以导航到localhost/api/my_categoy
其中my_category
是类别的名称/编号。