Note that there are some explanatory texts on larger screens.

plurals
  1. POPreserving output precision with Django DecimalField and PostgreSql Numeric field
    text
    copied!<p>I'm saving data to a PostgreSQL backend through Django. Many of the fields in my models are DecimalFields set to arbitrarily high max_digits and decimal_places, corresponding to numeric columns in the database backend. The data in each column have a precision (or number of decimal places) that is not known <em>a priori</em>, and each datum in a given column need not have the same precision.</p> <p>For example, arguments to a model may look like:</p> <pre><code>{'dist': Decimal("94.3"), 'dist_e': Decimal("1.2")} {'dist': Decimal("117"), 'dist_e': Decimal("4")} </code></pre> <p>where the keys are database column names.</p> <p>Upon output, I need to preserve and redisplay those data with the precision with which they were read in. In other words, after the database is queried, the displayed data need to look exactly like the data in that were read in, with no additional or missing trailing 0's in the decimals. When queried, however, either in a django shell or in the admin interface, all of the DecimalField data come back with many trailing 0's. </p> <p>I have seen similar questions answered for money values, where the precision (2 decimal places) is both known and the same for all data in a given column. However, how might one best preserve the exact precision represented by Decimal values in Django and numeric values in PostgreSQL when the precision is not the same and not known beforehand?</p> <p>EDIT:</p> <p>Possibly an additional useful piece of information: When viewing the table to which the data are saved in a Django dbshell, the many trailing 0's are also present. The python Decimal value is apparently converted to the maximum precision value specified in the models.py file upon being saved to the PostgreSQL backend.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload