Postgresql allows NaN
values in numeric columns according to its documentation here.
When defining Postgres tables using Django ORM
, a DecimalField
is translated to numeric
column in Postgres. Even if you define the column as bellow:
from django.db import models
# You can insert NaN to this column without any issue
numeric_field = models.DecimalField(max_digits=32, decimal_places=8, blank=False, null=False)
Is there a way to use Python/Django syntax to forbid NaN
values in this scenario? The Postgres native solution is to probably use some kind of constraint. But is that possible using Django syntax?
2
Answers
I don’t have a PostgreSQL database to test against but you can try creating a database constraint using a lookup based on the
IsNull
looukup:@MT0 answered the question. I just want to add that if you use a
DemimalField
and manipulate data in Django, you can normally not insertNaN
orInfinity
in the database. Indeed, Django itself checks if the value is finite (NaN
is not considered finite).Django first "prepares" the values to be representable in the database, and it does that with the
.get_db_prep_save(…)
method [GitHub]:Which calls the
.to_python(…)
function. The.to_python(…)
method [GitHub] then checks if theDecimal
is finite:It is of course better to add a constraint, since it might still be possible that some update queries eventually result in a
NaN
, but for simple insertions/updates through Django, this should not happen.