【问题标题】:Overriding Django Save and returning id if exists覆盖 Django Save 并返回 id(如果存在)
【发布时间】:2019-11-16 01:43:11
【问题描述】:

我正在使用 Django_rest 框架将文件上传到我的站点。但是,我经常上传同一个文件,所以我希望避免多次上传同一个文件。

为了克服保存同一文件的多个副本的问题,我覆盖了保存模型以上传文件并在文件已存在时将其删除。这很有效,尽管我觉得很多不需要上传。但是,我无法从我的序列化程序中返回现有的 id 以不执行此操作。有没有更好的解决方案?

模型.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)

【问题讨论】:

  • 嗨,有人对此有任何想法吗?很抱歉冒犯了这个问题。这让我很沮丧:)

标签: django django-rest-framework


【解决方案1】:

我设法通过更改此帖子来解决此问题 Django uploads: Discard uploaded duplicates, use existing file (md5 based check)

返回名称也会返回 id。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2016-01-18
    • 1970-01-01
    相关资源
    最近更新 更多