根据类别django drf

时间:2019-11-28 09:36:53

标签: django django-rest-framework

我想获取特定类别的图像,例如如果我发出get请求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')

api输出:

 [
    {
        "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'),

1 个答案:

答案 0 :(得分:1)

注意:您的序列化程序引用的模型(EventImage)未在上述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

N.B。我在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中都引用了它。

NB 。该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是类别的名称/编号。