Python Django初学者:显示RawQuerySet的值
我使用原始SQL查询来获取每周的销售记录,然后将其汇总并显示在网页上。我的问题是:Python Django初学者:显示RawQuerySet的值,python,django,Python,Django,我使用原始SQL查询来获取每周的销售记录,然后将其汇总并显示在网页上。我的问题是: sales = addCustomer.objects.raw("SELECT SUM(productPrice) FROM cms_addcustomer WHERE date <= %s and date >= %s", [startdate, weekDate]) 我已经阅读了关于堆栈溢出的大部分答案,但我无法理解它们,因为我是一个完全的初学者。如何解决此问题?您可以使用以
sales = addCustomer.objects.raw("SELECT SUM(productPrice) FROM cms_addcustomer WHERE date <= %s and date >= %s", [startdate, weekDate])
我已经阅读了关于堆栈溢出的大部分答案,但我无法理解它们,因为我是一个完全的初学者。如何解决此问题?您可以使用以下内容创建查询:
注意:通常Django模型中字段的名称是用snake_大小写的,而不是PerlCase,因此它应该是:
product_price
,而不是productPrice
您能否将您的
addCustomer
型号添加到问题中?您应该能够在不使用raw()
和使用aggregate()
的情况下执行此操作。您为什么要使用.raw(…)
而不仅仅是Django ORM?@IainShelvington我已将模型添加到问题中。@WillemVanOnsem我不确定如何执行此操作。我试着使用它的聚合,但这对我不起作用。基本上,我有三个单选按钮,可以每天、每周和每月过滤结果。我不知道如何正确使用聚合以及其中的日期条件。我认为基于这个问题,date\uuuuu范围
应该是另一种方式,以防这对操作不起作用。非常感谢@WillemVanOnsem!这很有魅力。我被困在这上面了。此外,从现在起,我将遵循snake_案例模式。非常感谢你的帮助@伊恩舍林顿感谢你指出这一点。我在使用(startDate,weekDate)时没有得到任何结果,但是在用(weekDate,startDate)替换它之后,我得到了结果。
from django.db import models
from datetime import date
class addCustomer(models.Model):
customerName = models.CharField(max_length=100)
productName = models.CharField(max_length=100)
productPrice = models.IntegerField()
date = models.DateField(default=date.today)
commission = models.IntegerField()
from django.db.models import Sum
total = addCustomer.objects.filter(
date__range=(weekDate, startDate)
).aggregate(
total_productprice=Sum('productPrice')
)['total_productprice']
class addCustomer(models.Model):
customerName = models.CharField(max_length=100)
productName = models.CharField(max_length=100)
productPrice = models.IntegerField()
date = models.DateField(auto_now_add=True, db_index=True)
commission = models.IntegerField()