#models.py
class Product(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000)
discount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000)
is_discount = models.BooleanField(default=False)
#views.py
def page(request):
product = Product.objects.get(pk=1)
I have main product price, sometime I need to enable discount price, so if I enabled it in "is_discount" and when I make product instance at result I need to get by product.price the value from "discount".
I understand that I can make it with
price = product.price
if product.is_discount:
price = product.discount
but this solution is not good for me.
Consider using a calculated field ( property
):
class Product(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000)
discount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000)
is_discount = models.BooleanField(default=False)
@property
def current_price(self):
return self.discount if self.is_discount else self.price
Product.objects.get(pk=1).current_price
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.