我在admin.py
中定义了一种方法来加税后金额:
def _grand_total(self, object_id):
line_amounts = Invoice_Line.objects.filter(appointment_ref=object_id).values_list('total_after_tax', flat=True)
return reduce((lambda x,y: x + y), line_amounts)
此行中定义的ORM查询:Invoice_Line.objects.filter(appointment_ref=object_id).values_list('total_after_tax', flat=True)
生成以下错误:
类型对象'Invoice_Line'没有属性'对象'
模型代码如下所示:
models.py:
class Appointment(models.Model):
create_date = models.DateField(auto_now_add=True, db_index=True)
appointment_ref = models.AutoField(primary_key=True)
appointment_date = models.DateField()
class Invoice_Line (models.Model):
appointment_ref = models.ForeignKey(Appointment, on_delete=models.CASCADE)
inv_line_date = models.DateTimeField(auto_now_add=True)
item_price = models.DecimalField(max_digits=7, decimal_places=2, default=00000.00, verbose_name='Service Amount')
tip_amount = models.DecimalField(max_digits=7, decimal_places=2, default=00000.00, verbose_name='Tip Amount')
item_quantity = models.PositiveSmallIntegerField(blank=False, null=True, default=0, verbose_name='Service Quantity')
total_before_tax = models.DecimalField(max_digits=7, decimal_places=2, default=00000.00, verbose_name='Before Tax')
stax_rate = models.DecimalField(max_digits=5, decimal_places=4, blank=True, null=True, verbose_name='Sales Tax Rate')
stax_amount = models.DecimalField(max_digits=7, decimal_places=2, default=00000.00, verbose_name='Sales Tax Amount')
total_after_tax = models.DecimalField(max_digits=7, decimal_places=2, default=00000.00, verbose_name='Total After Tax')
我在shell /解释器中运行相同的查询,并且效果很好。我可以协助您解决此错误吗?
任何帮助将不胜感激!
谢谢!
答案 0 :(得分:1)
解决了该问题:
正如我在问题中提到的,我已经在admin.py中定义了以下方法:
def _grand_total(self, object_id):
line_amounts = Invoice_Line.objects.filter(appointment_ref=object_id).values_list('total_after_tax', flat=True)
return reduce((lambda x,y: x + y), line_amounts)
我还已经在admin.py中注册了“ Invoice_Line”模型,如下所示:
@admin.register (Invoice_Line)
class Invoice_Line(admin.ModelAdmin):
list_display = ('__str__','inv_line_date','total_after_tax','appointment_ref')
readonly_fields = ('item_price','total_before_tax','stax_rate','stax_amount','total_after_tax')
问题是,您无法命名用于在admin.py中注册模型的类与在models.py中命名模型的方法完全相同。
换句话说,您不能这样做:
models.py:
class Invoice_Line (models.Model):
......
......
admin.py:
@admin.register (Invoice_Line)
class Invoice_Line (admin.ModelAdmin):
.......
.......
一旦我将admin.py中的类的名称更改为“ 类InvoiceLineAdmin(admin.ModelAdmin):”,则ORM查询就会产生我尝试修复的错误,效果很好。