擅长:python、mysql、java
<blockquote>
<p>Why Django DecimalField is able to return something else than Decimal
type?</p>
</blockquote>
<p>这是因为Django在模型创建过程中是允许的,并且允许您在这些字段中输入任何类型,如果您输入的内容可以强制为指定的类型,则不会出现错误。在</p>
<p>在将其插入数据库后,它将获得正确的类型。您可以使用<code>refresh_from_db()</code>来验证:</p>
<pre><code>article = Article.objects.create(unit_price="2.3")
type(article.unit_price)
>>> str
article.refresh_from_db()
type(article.unit_price)
>>> decimal.Decimal
</code></pre>
<blockquote>
<p>What would be the best way to ensure my app never deals with floats
for prices?</p>
</blockquote>
<p>确保这一点的唯一方法是在知道价格金额后立即将任何价格输入强制到<code>decimal.Decimal</code>。在</p>