Answer the question
In order to leave comments, you need to log in
Changing model fields on the fly?
In Django, I create a custom model with an encrypted field something like this:
class MyModelManager(models.Manager):
use_for_related_fields = True
def get(self, *args, **kwargs):
instance = super(MyModelManager, self).get(*args, **kwargs)
try:
instance.my_value = instance.decode_my_value()
except AttributeError:
pass
return instance
# Этот метод нужно как-то переопределить
def get_queryset(self, *args, **kwargs):
return super(MyModelManager, self).get_queryset(*args, **kwargs)
class MyModel(models.Model):
my_value = models.CharField(max_length=128)
objects = MyModelManager()
....
@property
def encode_my_value(self):
... алгоритм шифрации ...
return encoded
@property
def decode_my_value(self):
... алгоритм дешифрации ...
return decoded
# на лету шифруем данные в БД при сохранении
def save(self, *args, **kwargs):
self.my_value = self.encode_my_value()
super(MyModel, self).save(*args, **kwargs)
Answer the question
In order to leave comments, you need to log in
Create your class based on CharField by overriding the preparation methods for saving to the database and retrieving. (to_python, get_db_prep_value)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question