saran3h
saran3h

Reputation: 14122

How to get the money value without "$" using django-money?

I use django-money, then I have price field with MoneyField() in Product model as shown below:

# "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)),
        ]
    )

Then, when getting the price in views.py as shown below:

# "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")

I got the price with $ on console as shown below:

$12.54

Now, how can I get the price without $ as shown below?

12.54

Upvotes: 6

Views: 2865

Answers (2)

You can use .amount to get the price without $:

                              # Here
Product.objects.all()[0].price.amount

Then, you can get the price without $ on console as shown below:

12.54

Upvotes: 1

solarissmoke
solarissmoke

Reputation: 31514

You're dealing with a Money object (see here). That object has an amount property that will give you the decimal amount:

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

Which you can then convert to int if you want to.

Upvotes: 12

Related Questions