如何在使用django-money时获取没有"$"符号的货币值?

5

我使用 django-money,然后我在 Product 模型中有一个带有 MoneyField()price 字段,如下所示:

# "app/models.py"

from django.db import models
from djmoney.models.fields import MoneyField
from decimal import Decimal
from djmoney.models.validators import MaxMoneyValidator, MinMoneyValidator

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = MoneyField( # Here
        max_digits=5, decimal_places=2, default=0, default_currency='USD',
        validators=[
            MinMoneyValidator(Decimal(0.00)), MaxMoneyValidator(Decimal(999.99)),
        ]
    )

然后,在 views.py 中获取价格,如下所示:

# "app/views.py"

from app.models import Product
from django.http import HttpResponse

def test(request):
    print(Product.objects.all()[0].price) # Here
    return HttpResponse("Test")

我在控制台上得到了如下所示的价格:$

$12.54

现在,我如何获取下面没有美元符号$的价格?
12.54
2个回答

11

你正在处理一个Money对象(请查看这里)。该对象具有amount属性,该属性将为您提供十进制金额:

>>> price.amount
Decimal('12.54')

如果您想要的话,您可以将其转换为int


0
你可以使用.amount来获取没有$符号的价格:
                              # Here
Product.objects.all()[0].price.amount

然后,您可以像下面显示的那样在控制台上获取不带 $ 的价格:

12.54

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接