【问题标题】:Convert a price field in django to be in a specific currency将 django 中的价格字段转换为特定货币
【发布时间】:2019-03-21 20:34:44
【问题描述】:

我有一个 Product 模型,它有一个价格字段和一个货币字段。 用户可以使用不同的货币保存不同的产品。有些产品以美元保存,有些以 gbp 保存,等等'..

class Product(models.Model):


    price = models.DecimalField(decimal_places=1, 
                                max_digits=4, 
                                default=0)
    usd = 'USD'
    nis = 'NIS'
    gbp = 'GBP'
    CURRENCY_CHOICES = (
        (usd , 'USD'),
        (nis, 'NIS'),
        (gbp, 'GBP')
    )
    currency = models.CharField(
        max_length=3,
        choices=CURRENCY_CHOICES,
        default=usd,
        blank=True
    )

我希望能够以单一货币对所有产品进行分类和查看。 我如何添加一个字段price_in_usd,当设置“价格”和“货币”字段时,该字段将自动设置?

类似这样的例子:

price_in_usd = convert_price_to_usd()
convert_price_to_usd():
 if currency == GPB:
    return price*1.25
 if currency == NIS:
    return price*0.33

【问题讨论】:

  • 与其自己实现,不如使用django-money 之类的库。它支持货币之间的转换。
  • “我的问题是 django 没有 setter/getter”是什么意思???

标签: python django if-statement


【解决方案1】:

您可以使用clean() 方法来处理此类行为。

class Product(models.Model):

    price = models.DecimalField(decimal_places=1, max_digits=4, default=0)
    currency = models.CharField(
        max_length=3,
        choices=CURRENCY_CHOICES,
        default=usd,
        blank=True
    )
    price_in_usd = models.DecimalField(decimal_places=1, max_digits=4, default=0, editable=False)

    def clean(self):
        if self.price and self.currency:
            self.price_in_usd = convert_price_to_usd(self.price, self.currency)

请参阅Django docs 以准确了解何时调用clean() 方法。根据您的操作,您可能必须在调用save() 之前自己显式调用full_clean()。如果您使用 QuerySet.update() 或 bulk_create(),也不会调用 clean()。

另一种处理方式可能是使用触发器在 SQL 级别实现它。


但是,如果您希望以美元为单位的价格更新(每小时、每天或其他)以始终匹配当前的变化率,您将必须使用 cron 作业定期更新 price_in_usd。

如果您不需要在数据库级别按price_in_usd对数据进行排序,另一种解决方案是使用属性:

class Product(models.Model):

    price = models.DecimalField(decimal_places=1, max_digits=4, default=0)
    currency = models.CharField(
        max_length=3,
        choices=CURRENCY_CHOICES,
        default=usd,
        blank=True
    )

    @property
    def price_in_usd(self):
        return convert_price_to_usd(self.price, self.currency)

【讨论】:

  • 谢谢,我使用了 clean() 方法,效果很好。
猜你喜欢
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
相关资源
最近更新 更多