【问题标题】:How can I access the count of a field in Django model?如何访问 Django 模型中字段的计数?
【发布时间】:2022-11-14 08:14:20
【问题描述】:

我想显示总收入等于总价,总价是预约模型中的一个字段 我想要那个特定字段的计数,以便我可以在 HTML 中显示它。

class Appointment(models.Model):

    # Invoicing Section
    service_name = models.CharField(max_length=120, default='', blank=True, null=True)
    total_price = models.CharField(max_length=100,default='', blank=True, null=True)
    upfront_payment = models.CharField(max_length=100,default='', blank=True, null=True)
    grand_total = models.CharField(max_length=100,default='', blank=True, null=True)
    invoice_date = models.DateField(auto_now_add=True, blank=True, null=True)
    invoice_type_choice = (
            ('EVCPLUS', 'EVCPLUS'),
            ('SH.SO', 'SH.SO'),
            ('USD', 'USD'),
        )
    invoice_type = models.CharField(max_length=50, default='', blank=True, null=True, choices=invoice_type_choice)
    payment_status = models.CharField(max_length=10, choices=(('Pending', 'Pending'), 
        ('Completed', 'Completed'), ('Canceled', 'Canceled')), default='Pending')


    def __str__(self):
        return self.patient.patient_name

我试着这样做:

 revenue = Appointment.objects.filter(total_price = Appointment.total_price).count()

            return render(request, 'index.html', {
                'current_user': current_user,
                'sayfa': 'dashboard',
                'yearly_patients': yearly_patients,
                'monthly_appointments': monthly_appointments,
                'yearly_patients_graph': yearly_patients_dict,
                'monthly_appointments_graph':monthly_appointments_dict,
                'donutDataGraph': donutData,
                'appointments': appointments,
                'doctors': doctors,
                'revenue': revenue,
                'search_patient_form': form,
                'search_patient_form': search_patient_form
                })

但它返回 0 这是不正确的。

【问题讨论】:

  • 您能否粘贴您的代码而不是提供屏幕截图的链接?此外,很高兴知道您已经搜索和尝试过什么。
  • 对不起,我是新来的
  • 别担心。你的问题还不清楚。你想达到什么目标?您要检索数据库中所有约会记录的total_prices 的总和吗?
  • 这正是我想要的!

标签: python django django-models


【解决方案1】:

因此,您的方法存在一些问题。

首先,count()不计算总和,而是统计条目数。然而,这是一个好的开始,因为它聚合了数据库中的记录。

其次,.filter(total_price = Appointment.total_price) 没有任何意义。使用此语句,您可以将 db 值与字段类型进行比较。此外,如果您想聚合所有行,您也不想过滤您的记录。

第三,要求和,您需要有一个数字数据类型。但是,total_price 是文本数据类型 (CharField)。您将需要使用数字字段(例如 IntegerField 用于整数数量,或 DecimalField 用于具有固定小数位数的十进制数量):

total_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)

请注意,更改数据类型将需要您进行迁移,并且将文本转换为数字数据类型可能会失败。但是,处理这种迁移超出了这个问题的范围。

现在你有了数字数据类型,你可以做数字aggregations

from django.db.models import Sum
revenue = Appointment.objects.aggregate(revenue=Sum('total_price'))['revenue']

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 2020-11-09
    • 2020-03-03
    • 2013-03-16
    • 2011-03-13
    • 1970-01-01
    • 2011-01-01
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多