python - Django:处理定期付款时为客户和付款推荐的模型定义
问题描述
假设我有两个模型,一个 forCustomer
和一个 for Payment
。每个月我customer
都应该在每个月的 15 号之前付款。为了轻松获得当月未付款的客户报告,构建模型的最佳方法是什么?
客户型号:
class CustomerModel(models.Model):
first_name = models.TextField()
last_name = models.TextField()
email = models.EmailField()
付款模式:
class Payment(models.Model):
customer = models.ForeignKey(
Customer,
on_delete=models.SET_NULL,
null=True)
amount = models.FloatField()
date_received = models.DateField(auto_now=False)
解决方案
我们可以利用.exclude(..)
这里来排除已经付款的人,比如:
from datetime import date
month_day = date.today() # specify a day in the month to check
from_date=month_day.replace(day=1) # the first of the current month
to_date=month_day.replace(day=15) # the 15th of the current month
Customer.objects.exclude(
payment__date_received__gte=from_date
payment__date_received__lte=to_date
)
或更优雅的__range
查找:
Customer.objects.exclude(
payment__date_received__range=(from_date, to_date)
)
如果我们今天运行这个(month_day
等于 2018 年 10 月 15 日),我们将得到所有在 10 月1日到 10 月 15 日之间没有与with建立关系的Customer
s 。这个月的任何一天都会发生同样的事情。例如设置为,获取2017年12月1日至2017年12月15日期间所有未付款的客户。payment
date_received
month_day
date(2017, 12)
请注意,也许并非所有客户当时都开始使用您的服务(或已经取消订阅)。在这种情况下,这些Customer
s 将因此被列出,因此可能需要进行一些重构以使其更可用。
推荐阅读
- ios - 启动音频会话时,无法识别的选择器发送到实例 0x7fc32dc066d0'
- google-cloud-platform - Terraform 覆盖远程后端上的状态文件
- iframe - 博客上的 iframe 高度 100%
- asp.net - 我想通过我的 ASP.Net 网站发送电子邮件
- java - 等到firebase数据检索数据
- django - 如何在 FileField django 中删除 PK 和文件?
- jwt - JSON Web Token Based 身份验证如何无状态?
- typescript - 声明泛型类型的 const
- ios - 检索与其父类别相关的对象属性
- java - 如何使用 Mockito 模拟类数组