Django IntegerField返回字符串(!)-如何强制转换为int? [英] Django IntegerField returning string(!) - how to coerce to int?

查看:102
本文介绍了Django IntegerField返回字符串(!)-如何强制转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型上声明了一个IntegerField,如下所示:

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.

这让我感到有些惊讶:如果IntegerField在赋值时(或者最晚在保存时)将其值强制为整数,那就太好了,因此用户可以依靠它为整数.

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.

(我的应用程序使用sqlite.)

(My application uses sqlite.)

有没有办法使IntegerField只返回整数?还是我必须创建一个自定义字段才能做到这一点?

推荐答案

正如我的评论中提到的,发生这种情况的原因是Django在保存时对字段执行了相关的强制,但没有将值更改反映到原始字段上模型,因为不重新查询数据库就无法完成.

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.

这篇关于Django IntegerField返回字符串(!)-如何强制转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆