Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

could not actually find how from_db_value works in django source code?

I have a some fields in my model where I am trying to apply encryption on all the fields. Each field encryption depends on the values of two other fields in that same model class. I am able to achieve the encrypted data. But I also need those two other fields in the same class to decrypt the other field values that is returned by the function def from_db_value(self, value, expression, connection, *args).

I have read the docs and source code, but I didn't see a proper explanation on the following parameters in from_db_value(self, value, expression, connection, *args):

  1. expression
  2. *args

I want to know how and where we can supply these parameters. How else we can use that function. I know the function should return the value from database converted into an appropriate python object. But I want to know what else it can do or we can do with it?

P.S: Yes, I am trying to make custom field classes. Inspiration: django-fernet-fields

like image 313
Vkyishq Avatar asked Sep 14 '25 03:09

Vkyishq


1 Answers

I don't know how far you want to go down the rabbithole, but maybe this helps. As you probably already found from_db_value is used in the Field class in django.db.models.fields.__init__.py line 708. It's used here as a way to hook into the value conversion for models for specific databases. For example it is used to convert to native PostGreSQL array field.

If you dig a little deeper you'll find these converters are used by the SQLCompiler class in django.db.models.sql.compiler.py line 1084. Which in turn is called by results_iter below it.

I noticed the how-to guide doesn't mention using and *args argument in the method definition. So I don't know where that comes from.

like image 52
Exelian Avatar answered Sep 15 '25 18:09

Exelian