覆盖Django保存并返回ID(如果存在)

时间:2019-07-05 12:08:38

标签: django django-rest-framework

我正在使用Django_rest框架将文件上传到我的网站。但是,我经常上载相同的文件,因此我希望避免多次上载相同的文件。

为克服保存同一文件的多个副本的问题,我覆盖了保存模型以上传文件并删除该文件(如果已存在)。尽管我认为很多不需要上传,但此方法有效。但是,我无法从序列化程序中返回现有的ID,因此无法执行此操作。有更好的解决方案吗?

Model.py

    class IMAGES(models.Model):



        IMAGE = models.FileField(max_length=150,upload_to='documents/%Y/%m/%d')

        def __unicode__(self):
            return str(self.id)



        def save(self, *args, **kwargs):

            imstring="documents/" + datetime.now().strftime('%Y') + "/" + datetime.now().strftime('%m')  + "/" + datetime.now().strftime('%d') + "/" + str(self.IMAGE)

            try:
                this = IMAGES.objects.filter(IMAGE=imstring)[0] # This sees if the filename is already in the database.

                if this.IMAGE: # if it is,
                    # delete the file and replace it.
                    os.remove(this.IMAGE.path) 
            except IndexError:
                pass

            except ObjectDoesNotExist:
                pass

            super(IMAGES, self).save(*args, **kwargs)

serializer.py

class IMAGESEntrySerializer(serializers.ModelSerializer):
    class Meta:
        model =  IMAGES
        fields = (
            'id', 'IMAGE')

    def create(self, validated_data):


        result, other =  IMAGES.objects.get_or_create(**validated_data)

        return result

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.NAME = validated_data.get('NAME', instance.title)
        instance.save()
        return instance

views.py

class IMAGESADD(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):

    queryset = IMAGES.objects.all()
    serializer_class = IMAGESEntrySerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):

        return self.create(request, *args, **kwargs)

1 个答案:

答案 0 :(得分:0)

我希望通过更改此信息来解决此问题 Django uploads: Discard uploaded duplicates, use existing file (md5 based check)

返回名称也返回ID。