问题
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