[Fixed]-Do field types for Django's models have any kind of field that behaves like JavaScript's Numbers?

1đź‘Ť

âś…

No, there aren’t.

Django’s model fields store data in the database using the database’s native types. The purpose of a “field type” is to tell Django, “When saving this, save it as this type.” They also specify how the value stored should be mapped back into a native Python type.

So, since a database like Postgres doesn’t have a “magic” Number storage type, and because Python doesn’t have a native “magic” Number type, it would not make sense to have a Django field type that represented a magic type.

Instead, you just have to pick an integer type to store your data as, and stick to it whenever reading or writing that field.

👤Jack Shedd

0đź‘Ť

I think the most straightforward way to get what you’re after is to use a FloatField for storage and a custom template filter for display.

Python floats have an is_integer() method that makes it easy to tell whether the float is exactly equivalent to an integer. Your template filter would look something like this:

def intify(value):
    return int(value) if value.is_integer() else value

Another option would to be to write a custom model field that inherits from FloatField and converts the value into either a Python int or float depending on the specific value. However, I’d be wary of allowing the underlying Python type to change since there are situations where int and float behave differently.

Leave a comment