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.
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.
- Django error on simple app while run the program
- Getting error in mixins when I try to login as a user
- Django use URL tag in template from app specific urls?
- Return data from $.ajax to use later
- Child object by Parent