When saving, how can you check if a field has changed?

前端 未结 25 2134
鱼传尺愫
鱼传尺愫 2020-11-22 07:15

In my model I have :

class Alias(MyBaseModel):
    remote_image = models.URLField(max_length=500, null=True, help_text=\"A URL that is downloaded and cached          


        
25条回答
  •  一整个雨季
    2020-11-22 07:29

    Another late answer, but if you're just trying to see if a new file has been uploaded to a file field, try this: (adapted from Christopher Adams's comment on the link http://zmsmith.com/2010/05/django-check-if-a-field-has-changed/ in zach's comment here)

    Updated link: https://web.archive.org/web/20130101010327/http://zmsmith.com:80/2010/05/django-check-if-a-field-has-changed/

    def save(self, *args, **kw):
        from django.core.files.uploadedfile import UploadedFile
        if hasattr(self.image, 'file') and isinstance(self.image.file, UploadedFile) :
            # Handle FileFields as special cases, because the uploaded filename could be
            # the same as the filename that's already there even though there may
            # be different file contents.
    
            # if a file was just uploaded, the storage model with be UploadedFile
            # Do new file stuff here
            pass
    

提交回复
热议问题