将Django中的价格字段转换为特定货币

时间:2018-10-17 08:14:14

标签: python django if-statement

我有一个产品模型,其中有一个价格字段和一个货币字段。 用户可以使用不同的货币保存不同的产品。某些产品保存在usd中,某些产品保存在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

1 个答案:

答案 0 :(得分: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()方法。根据您的操作,在致电full_clean()之前,您可能必须自己明确地致电save()。另外,如果您使用clean()QuerySet.update()例如,bulk_create()也不会被调用。

处理此问题的另一种方法可能是在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)
相关问题