简体   繁体   English

Django 更改查询集中的字段值

[英]Django change field value in queryset

#models.py #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 #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".我有主要产品价格,有时我需要启用折扣价,所以如果我在“is_discount”中启用它,当我在结果中创建产品实例时,我需要通过 product.price 从“折扣”中获取值。

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 ):考虑使用计算字段 ( 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM