简体   繁体   English

Django order_by 价格字段与链接货币字段

[英]Django order_by price field with linked currency field

I have real estate model.我有房地产 model。 There are two fields price and currency .有两个字段pricecurrency 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 1 美元 = 10 000 乌兹别克斯坦

10 000 UZS = 1 USD 10 000 乌兹别克斯坦 = 1 美元

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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