Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply md5 function to field in django orm?

How can I generate this sql query from model without using objects.raw() method? DB is MySQL.

SELECT * FROM model_table WHERE MD5(field) = 'my value';
like image 870
demon.mhm Avatar asked Aug 27 '14 10:08

demon.mhm


1 Answers

Do you have two ways:

First way: Extra

Extra method: Entry.objects.extra(where=["MD5(field) = 'my value'"])

Pros: fast coding.

Cons: not index friendly, full scan, poor performance.

Second way: new field

Adding new field on model, field_md5 and set it on save.

import hashlib
myModel(models.Model):
    field = models.CharField(max_length=30)
    field_md5 = models.CharField(max_length=16, editable = false )

    def save(self, *args, **kwargs):        
        self.field_md5 = hashlib.md5.new(self.field).digest()
        super(Model, self).save(*args, **kwargs)

Pros: fast performance.

Cons: database changes required.

EDIT: In python3 use

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

instead of:

...
super(Model, self).save(*args, **kwargs)
...
like image 140
dani herrera Avatar answered Sep 21 '22 20:09

dani herrera