首页 > 解决方案 > 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)

标签: pythondjango

解决方案


我们可以利用.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建立关系的Customers 。这个月的任何一天都会发生同样的事情。例如设置为,获取2017年12月1日至2017年12月15日期间所有未付款的客户。paymentdate_receivedmonth_daydate(2017, 12)

请注意,也许并非所有客户当时都开始使用您的服务(或已经取消订阅)。在这种情况下,这些Customers 将因此被列出,因此可能需要进行一些重构以使其更可用。


推荐阅读