byoungb
byoungb

Reputation: 1801

Custom Django Model Field (lazy encryption/decryption)

Is there a method that can be overridden that is only called when the field is loaded from the database.

I have an encrypted field from a legacy table, (that has no prefix, or identifying format that can be reliably used to determine if it is encrypted or not.)

My decryption code cannot go in the to_python function because it is called not only when loaded from the database.

To make things worse, I wanted to make the decryption and encryption lazy, so that I do not have to make calls to decrypt/encrypt unless it is required. (the encryption code is a weird flavor of AES in ASP classic, so I created an asp service that I can call from python. And it is painfully slow) I used django's lazy function to create a nice decrypt_lazy function but without being able to know if the value is encrypted or not I am stuck.

So to reiterate my main question is... is there a method or hook I can use on a custom model field that is used to process the value only when the value comes from the database. And again to_python does not work for me since it is called and passed values from other places.

Upvotes: 0

Views: 990

Answers (1)

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

You can simply use a @property method when you need decrypted value of a field -

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    pin = models.CharField(max_length=30)

    @property
    def pin_decrypted(self):
        # decrypt self.pin and return
        return magic_decrypt_method(self.pin)

Now you can either access person.pin or person.pin_decrypted.

Upvotes: 3

Related Questions