簡體   English   中英

在 Django 模型中執行算術運算后,如何使用獲得的新值更新模型中整數的值?

[英]After performing arithmetic operations within a django model, how can I update the value of an integer in my model using the new value I obtained?

我下面的代碼來自這個問題

class CryptoData(models.Model):
    currency = models.CharField(max_length=20, choices=currency_choices, default='BTC')
    amount = models.IntegerField()
    price_with_amount = 1


    def calculate_price(self):
        if self.currency == "BTC":
            currency_price = get_crypto_price("bitcoin")
        elif self.currency == "ETH":
            currency_price = get_crypto_price("ethereum")
        elif self.currency == "UNI":
            currency_price = get_crypto_price("uniswap")
        elif self.currency == "ADA":
            currency_price = get_crypto_price("cardano")
        elif self.currency == "BAT":
            currency_price = get_crypto_price("basic attention token")

        price_with_amount = currency_price * self.amount

        return price_with_amount

    def save(self,*args,**kwargs):
        self.price_with_amount = self.calculate_price()
        super().save(*args, **kwargs)


    class Meta:
        verbose_name_plural = "Crypto Data"


    def __str__(self):
        return f'{self.currency}-{self.amount}-{self.price_with_amount}'

基本上,我想將用戶輸入的金額乘以我使用 get_crypto_price 函數獲得的價​​格(我已經確認 get_crypto_price 函數有效)。 保存 self.price_with_amount 后,我​​想在我的str方法中返回它,然后將它傳遞給我的 views.py 以在我的 HTML 中使用。 例如,當我將 price_with_amount 的值設為 1 時,就像我在代碼中所做的那樣,它會通過並在我的 HTML 中正常工作。 我想要做的是將 price_with_amount 的值更改為方法calculate_price 中獲得的值。 如何在保持我目前擁有的方法的同時做到這一點?

謝謝 :)

如果你真的想把它保存到數據庫中,你可以使用editable=False參數使該字段成為一個models.FloatField ,這樣它就不會出現在用戶編輯的表單中。 然后您的其余代碼應該按原樣工作。

但...

由於price_with_amount是基於當前價格的動態值,因此通過get_crypto_price函數保存它似乎不是一個好主意。

相反,您可以使用@property即時計算值。 property是一個實例方法,您可以像使用常規屬性一樣使用它。

你的代碼可以這樣重寫:

class CryptoData(models.Model):
    currency = models.CharField(...)
    amount = models.IntegerField()

    ...

    @property
    def price_with_amount(self):
        return self.calculate_price()

    def __str__(self):
        return f'{self.currency}-{self.amount}-{self.price_with_amount}'

使用此實現,您始終可以訪問CryptoData實例上的price_with_amount屬性,只要它具有currencyamount值,它就會顯示按需計算的值。

>>> crypto = CryptoData(currency="ETH", amount=10)
>>> crypto.price_with_amount
22718.20
>>> crypto.save()

# It still behaves as expected after fetching it from the db
>>> CryptoData.objects.get(id=crypto.id).price_with_amount
22718.20

# You can use the property just like you would a regular attribute
>>> if crypto.price_with_amount > 1000:
        print("foobar")
foobar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM