Mik*_*keN 92 django django-models
我需要在Django模型的字段中存储一美元金额.什么是最好的模型字段类型?我需要能够让用户输入这个值(通过错误检查,只需要一个精确到美分的数字),格式化输出给不同地方的用户,并用它来计算其他数字.
sim*_*rsh 143
一个小数领域是货币价值的正确选择.
它看起来像:
credit = models.DecimalField(max_digits=6, decimal_places=2)
Run Code Online (Sandbox Code Playgroud)
Lee*_*nde 34
field = models.DecimalField(max_digits=8, decimal_places=2)
Run Code Online (Sandbox Code Playgroud)
请注意,max_digits应为> = decimal_places.此示例设置允许的值最大为:999,999.99
文件:https://docs.djangoproject.com/en/1.10/ref/models/fields/#decimalfield
Mic*_*son 30
其他答案100%正确,但不太实用,因为您仍然需要手动管理输出,格式等.
我建议使用django-money:
from djmoney.models.fields import MoneyField
from django.db import models
def SomeModel(models.Model):
some_currency = MoneyField(
decimal_places=2,
default=0,
default_currency='USD',
max_digits=11,
)
Run Code Online (Sandbox Code Playgroud)
从模板自动工作:
{{ somemodel.some_currency }}
Run Code Online (Sandbox Code Playgroud)
输出:
$123.00
Run Code Online (Sandbox Code Playgroud)
它有一个强大的后端通过python-money,它实际上是标准十进制字段的替代品.
定义小数并在值前面返回$符号.
price = models.DecimalField(max_digits=8, decimal_places=2)
@property
def price_display(self):
return "$%s" % self.price
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41112 次 |
| 最近记录: |