Django IntegerField returning string(!) - how to coerce to int?

≯℡__Kan透↙ 提交于 2021-02-07 14:41:32

问题


I have an IntegerField declared as below on a model:

amount = models.IntegerField()

When accessing it, it sometimes returns a string. The proximate cause for this is that it has had a string assigned to it. So far, so unmysterious. It also returns a string even after it has been saved.

This strikes me as a little surprising: it would be nice if IntegerField coerced its value to an integer on assignment (or, at the latest, on save), so the user could rely on it being an integer.

(My application uses sqlite.)

Is there a way to make IntegerField only return ints? Or do I have to create a custom field to do this?


回答1:


As mentioned in my comment, the reason this is happening is that Django performs relevant coercions on fields at save, but doesn't reflect value changes back on the original model because it can't be done without querying the database again.

The quickest fix (and easiest, in the long run) for this kind of problem is to find the source of the string and turn it into an int - to me it would indicate there's something amiss earlier in the validation that should be picking this up.



来源:https://stackoverflow.com/questions/9395106/django-integerfield-returning-string-how-to-coerce-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!