I am using Django_rest framework to upload files to my site. However, often I am uploading the same file, so I wish to avoid uploading the same file multiple times.
To overcome saving multiple copies of the same file, I have overwritten the save model to upload a file and delete the file if it already exists. This works although I feel it is alot of not needed uploading. However, I can't get the existing id to be returned from my serialiser to not do this. is there a better solution to this?
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)