How to query ImageField by File

Hi,

So let’s say i have this model.

class Image(models.Model):
    image = models.ImageField(upload_to='media')

    class Meta:
        verbose_name = "Image"

So now i have a random image ( note that the filename for the image saved on the database and the image i have has different filename but same extension )

How to check if the following image exists in database ( i know django can’t directly query ImageField | or can it? )

Am I am looking for some sort of hashing algorithm/field ( like with imagehash )? ( this is my initial idea )

I was looking for something like

my_image = ... # a random image that i got from POST
Image.objects.get(image=my_Image)

You could calculate the MD5/SHA1 of the image and store this in a separate column in your table, then when you come to check if the image exists you calculate the MD5/SHA1 of the current image and then check that it matches in the database.

Both MD5 and SHA1 are hashing algorithms . MD5 is simple and fast, but it does not provide good security. SHA1 is complex as compared to MD5 and it provides greater level of security.

Here is a well documented article around it StackOverflow .

As for what you’re seeking, no there isn’t any way which implements this Algorithm in the backend and gives you a direct function of:

my_image = ... # a random image that i got from POST
Image.objects.get(image=my_Image)
1 Like

Thanks. Do you know how to re-query the database to get the image from hash ( for django specifically ) ?