V
V
Vladimir Kuts2016-03-30 12:05:49
Django
Vladimir Kuts, 2016-03-30 12:05:49

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)

The field is encrypted "on the fly" as it should be, and the already encrypted value is stored in the database.
When MyModel.objects.get(id=some_id).my_value is called, the field is decoded "on the fly"
All is well, but it doesn't work for MyModel.objects.get_queryset()
Now the question is how to add a manager so that it returns a QuerySet with already decrypted values ​​of the my_value fields. The manager has a get_queryset method for this, it operates with a QuerySet, and I can’t figure out how to change the required field there.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2016-03-30
@deliro

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 question

Ask a Question

731 491 924 answers to any question