我想按费用类型对费用进行每月明细。 我想通过过滤器表单动态输入开始日期和结束日期,这样我就不必为每个月重复代码。
对于每种类型的费用,我创建了一个单独的查询集(超过 20 个)。
这是视图.py
def monthly_analysis_november(request):
accountant = Expenses.objects\
.filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "accountant expenses")\
.annotate(price=Sum(F('quantity')*F('price_per_unit')))\
.aggregate(total_accountant=Sum('price'))
interest_rates = Expenses.objects\
.filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "interest rates")\
.annotate(price=Sum(F('quantity')*F('price_per_unit')))\
.aggregate(total_interest_rates=Sum('price'))
phones = Expenses.objects\
.filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "phones")\
.annotate(price=Sum(F('quantity')*F('price_per_unit')))\
.aggregate(total_phones=Sum('price'))
oil = Expenses.objects\
.filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "oil")\
.annotate(price=Sum(F('quantity')*F('price_per_unit')))\
.aggregate(total_oil=Sum('price'))
leasing = Expenses.objects\
.filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "leasing")\
.annotate(price=Sum(F('quantity')*F('price_per_unit')))\
.aggregate(total_leasing=Sum('price'))
other_expenses = Expenses.objects\
.filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "other")\
.annotate(price=Sum(F('quantity')*F('price_per_unit')))\
.aggregate(total_other_expenses=Sum('price'))
...
这是我创建的 model.py
class Expenses(models.Model):
date = models.DateField()
place_of_expense = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, blank=True, null=True)
TYPE_OF_EXPENSE_CHOICES = (
("oil", "oil"),
("leasing", "leasing"),
("material", "material"),
("land leasing", "land leasing"),
("spare parts", "spare parts"),
("tools and equipment", "tools and equipment"),
("services", "services"),
("accountant expenses", "accountant expenses"),
("interest rates", "interest rates"),
("phones", "phones"),
("other", "other"),
...
)
type_of_expense = models.CharField(blank=True, null=True, max_length=25, choices=IZBOR_VRSTE_TROSKA, default = "Gorivo")
expense_description = models.CharField(max_length=255)
unit = models.CharField(blank=True, null=True, max_length=20, choices=IZBOR_JEDINICE_MERE, default = "l")
quantity = models.DecimalField(max_digits=10, decimal_places=2)
price_per_unit = models.DecimalField(max_digits=10, decimal_places=2)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, blank=True, null=True)
我在应用程序的其他部分使用了 django-filters,但在这里我无法实现它。 目前,我每个月都有相同的视图函数,但这是大量重复的代码。唯一的区别是 date__gte 和 date__lte。 是否有可能使用 django-filters 或其他方式来做到这一点?
查看 Djanog-filter 文档 我认为您需要做的就是创建一个过滤器类,如下所示:
date__gte