我有两个django模型,一个是"公司",另一个是公司的"MonthlyReport"

class Company(models.Model):
name = models.CharField(max_length=50)


class MonthlyReport(models.Model):
    company = models.ForeignKey(Company,on_delete=models.CASCADE)
    sale = models.IntegerField()
    date = models.DateField()

我怎样才能找到一家销售额比上个月高出20%的公司来解决这个问题

推荐答案

您当然可以使用ORM来完成.您需要将Max(或SUM,取决于您的用例)与Q()表达式过滤器相结合,并在过滤之前将百分比增加注释到queryset.

您可以在一段代码中完成,但我已经将其拆分了,因为获取日期和查询表达式相当长.我还将增加值放在一个单独的变量中,而不是硬编码.

from datetime import datetime, timedelta
from django.db.models import Max, Q

SALES_INCREASE = 1.2

# Get the start dates of this month and last month
this_month = datetime.now().date().replace(day=1)
last_month = (this_month - timedelta(days=15)).replace(day=1)

# Get the maximum sale this month
amount_this_month = Max('monthlyreport__sale', 
    filter=Q(monthlyreport__date__gte=this_month))

# Get the maximum sale last month, but before this month
amount_last_month = Max('monthlyreport__sale', 
    filter=Q(monthlyreport__date__gte=last_month) & \
        Q(monthlyreport__date__lt=this_month))

Company.objects.annotate(
    percentage_increase=amount_this_month/amount_last_month
    ).filter(percentage_increase__gte=SALES_INCREASE)

Edit-更新答案,如果我们想删除Company:

# use the same imports and date variables

# Get the maximum sale this month
amount_this_month = Max('sale', filter=Q(date__gte=this_month))

# Get the maximum sale last month, but before this month
amount_last_month = Max('sale', filter=Q(date__gte=last_month) & \
        Q(date__lt=this_month))

MonthlyReport.objects.annotate(
    percentage_increase=amount_this_month/amount_last_month
    ).filter(percentage_increase__gte=SALES_INCREASE)

Django相关问答推荐

当RST =True时RST CSS

如何根据属性的 Select 对查询集进行排序

Django/SendGrid-密码重置-发件人地址与验证的发件人身份不匹配.";

Urls.py中路径**kwargs的Django翻译?

如何在两个字段上查找 django 模型的副本?

Pymongo:搜索文档时忽略空输入值

包含资源时,DRF 返回我的软删除记录

在模板中调用 FileField 对象会呈现不正确的路径

在 settings.py 中指定 Django 测试数据库名称

Django ORM 和锁定表

Django:在模板中显示当前语言环境

Django - 强制执行 ManyToManyField 唯一项

在 django web 应用程序中,如何给用户自己的子域?

django 复数模板

始终将用户包含在 django 模板上下文中

Django JavaScript 文件

django 模板中对象的模型名称

如何向所有 Django 响应添加 HTTP 标头

django.db.utils.OperationalError 无法连接到服务器

Django 测试 - 在所有测试中修补对象