如何使用 @property 装饰器和注释 Django 查询集

问题描述 投票:0回答:1

模型.py

class InvoiceItem(models.Model):
    quantity = models.IntegerField()
    items_price = models.ForeignKey(PriceMaster,on_delete=models.CASCADE)
    invoices = models.ForeignKey(Invoice, on_delete=models.CASCADE,null=True,blank=True)
    create_at = models.DateField(auto_now_add=True)
    create_by = models.ForeignKey(User, on_delete=models.CASCADE)
    
    @property
    def net_amount(self):
        self.total = self.quantity * self.items_price.price 
        self.gst = self.total * self.items_price.gst.gst / 100
        self.net_total = self.total + self.gst
        return self.net_total

查看.py

invoiceItem_id=InvoiceItem.objects.values("invoices__id","invoices__invoice_no","invoices__create_by__username","invoices__create_at","invoices__status").annotate(total = Sum('net_amount'))

**我们可以在上述场景中使用@property装饰器**

django django-models django-queryset
1个回答
0
投票

不,使用

.values(…)
 [Django-doc]/
.values_list(…)
 [Django-doc]
通常不是一个好主意,因为这是一个 原始痴迷反模式[refactoring.guru]:它将生成字典(或元组)。因此,这些模型对象不再附带您传递给模型的所有逻辑。例如,它不能再跟随
ForeignKey
s,您不能将其转换为模型中指定的
str
ing,等等。

使用

.values(…)
通常只有几个用例,其中一个是按某一组项目进行聚合,在这种情况下,您无论如何都不需要属性,而只需要您定义的聚合。您可以使用
.only(…)
 [Django-doc]
限制列的选择以减少带宽。无论如何,使用模型的整个想法是通过方法、属性等中定义的“结构”和“额外逻辑”来传送数据。

© www.soinside.com 2019 - 2024. All rights reserved.