首页 > 解决方案 > 如何在 DjangoRestFramework 中实现按图像搜索功能?

问题描述

我正在构建一个应用程序,它允许用户将图像上传到服务器,服务器将返回数据库中最相似的图像。我实现了一个基本算法来做到这一点,但我无法弄清楚如何让用户将图像上传到服务器。我正在使用 DjangoRestFramework。

我现在已经实现了通过实现 ViewSet 和 CreateModelMixin 来将图像上传到数据库的功能。但是我想让用户上传图像,运行我的算法,然后返回最相似图像的 ID。我应该研究什么功能/视图集?我是 REST 的初学者

标签: djangorestdjango-rest-frameworkdjango-rest-viewsets

解决方案


我将通过允许序列化程序在这种情况下完成繁重的工作并保持视图苗条来解决这个问题。

class ImageUploadSerializer(serializers.Serializer):
     """
     This serializer will accept the uploaded image, 
     run the custom algorithm and return the queryset
     of the similar images.
     """
     [#read more about image field in docs][1]
     image = serializers.ImageField(write_only=True)
     similar_image = serializers.ImageField(read_only=True)

     def get_similar_image(self, obj):
         """
         Sends the image to the custom alogrithm
         and returns the most similar image
         """
         
         # your function to return the similar image  
         return most_similiar_image(self.validated_data.get("image"))

    class Meta:
        fields = ("image", "similar_image")

推荐阅读