gpt4 book ai didi

python - 将 django 中的价格字段转换为特定货币

转载 作者:行者123 更新时间:2023-12-01 08:54:48 25 4
gpt4 key购买 nike

我有一个产品模型,其中包含价格字段和货币字段。用户可以使用不同的货币保存不同的产品。有些产品以美元保存,有些以英镑保存,等等'..

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




最佳答案

您可以使用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)

关于python - 将 django 中的价格字段转换为特定货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52850211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com