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';
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)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With