简体   繁体   中英

Django order_by price field with linked currency field

I have real estate model. There are two fields price and currency . People can enter real estate's price in two currency only. However as price field is just numbers and prices are linked to currency, I can not order prices with different currency. Only ordering with the same currency is possible.

Only two currency options are available:

UZS = 'UZS'
USD = 'USD'

CURRENCY_TYPES = (
    (UZS, 'sum'),
    (USD, 'y.e.')
)

class Property(BaseModel):
    price = models.PositiveIntegerField()
    currency = models.CharField(max_length=255, choices=CURRENCY_TYPES)

I tried to change prices to the same currency but then I don't know how to order them.

Property.objects.filter(currency='UZS').annotate(divided_price=F('price') / 10000).values('divided_price')

So rate is

1 USD = 10 000 UZS

10 000 UZS = 1 USD

How to order prices with different currencies?

Use case expression for converting the prices to a common currency value. For example

from django.db.models import Case, When

#...
conversion_rate = 1 / 10_000 # This value can be from an exchange board

qs = Property.objects.annotate(
    price_usd=Case(
        When(currency=UZS, then=F('price') * conversion_rate ),
        # Assumes that the only other currency is USD
        default=F('price')
    )
).order_by('price_usd')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM