Cdecimal and SQLAlchemy actually stores `decimal.Decimal`?

The django + SQLAlchemy application uses cdecimal instead of the default decimal module. I followed the instructions on the SQLAlchemy website:

import sys import cdecimal sys.modules["decimal"] = cdecimal 

Using the same from the previous stackoverflow, I can add data to the database. However, when I retrieve a record from my table and look at its value, the type of the value returned to me is actually equal to decimal.Decimal , not cdecimal.Decimal .

How to tell SQLAlchemy to return cdecimal.Decimal objects when retrieving records?

Thanks!

+4
source share
3 answers

The solution here is to put this code

 import sys import cdecimal assert "sqlalchemy" not in sys.modules assert "decimal" not in sys.modules sys.modules["decimal"] = cdecimal 

In the manage.py file, not in the models.py file. This ensures that cdecimal really replaces the decimal number from the beginning.

+3
source

SQLAlchemy is not able to load the decimal module after fixing it with cdecimal . Therefore, in this case, you need to make sure that you perform the sys.modules change before SQLalhcemy is installed:

 import sys import cdecimal assert "sqlalchemy" not in sys.modules assert "decimal" not in sys.modules sys.modules["decimal"] = cdecimal 

Edit: Also make sure you run sys.modules["decimal"] to actually replace the replacement with "decimal".

+3
source

You can change decimal to cdecimal more reliable way, forcing it to happen before any other code runs. When launched, the Python interpreter will read any .pth files and execute any import statements it contains, which allows us to run code before executing any program. I documented the cdecimal swap cdecimal more detail on my blog - essentially you need to create two files:

First site-packages/my_patches.pth , which contains:

 import my_patches 

Secondly, site-packages/my_patches.py , which contains the swap code:

 import sys import cdecimal # Ensure any import of decimal gets cdecimal instead. sys.modules['decimal'] = cdecimal 

Then you should not have problems with SQLAlchemy, since it will not be able to run a preliminary replacement.

0
source

Source: https://habr.com/ru/post/1401224/


All Articles