You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django如何实现事件重复触发或创建周期recurring事件

模型改造实现周期重复事件

原单个date字段无法承载重复规则的多维度信息,需要新增重复规则相关字段,修改后的Event模型代码如下:

from django.db import models
from django.contrib.auth.models import User

class Event(models.Model):
    # 重复类型枚举
    RECURRENCE_CHOICES = [
        ('NONE', '不重复'),
        ('WEEKLY', '每周重复'),
        ('MONTHLY', '每月重复'),
    ]
    title   = models.CharField(max_length=50)
    author  = models.ForeignKey(User, verbose_name=("author"), on_delete=models.CASCADE)
    body    = models.TextField()
    # 替换原date字段为事件首次发生时间
    start_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    # 重复规则截止时间,为空代表永久重复
    recurrence_end = models.DateTimeField(null=True, blank=True)
    # 重复类型
    recurrence_type = models.CharField(max_length=10, choices=RECURRENCE_CHOICES, default='NONE')
    # 周重复用:存储选中的星期,值为0-6对应周日到周六,例如[1,3]代表周一周三重复
    recurrence_week_days = models.JSONField(null=True, blank=True)
    # 月重复用:存储选中的月日期,值为1-31,例如[10,20]代表每月10号、20号重复
    recurrence_month_dates = models.JSONField(null=True, blank=True)

注意:Django 3.1及以上版本原生支持JSONField,低于该版本需要单独安装适配的JSONField依赖包

业务逻辑适配
  • 周重复场景:查询事件时,根据recurrence_week_days存储的星期值,生成查询时间范围内所有匹配的时间点
  • 月重复场景:查询事件时,根据recurrence_month_dates存储的日期值生成匹配时间点,若当月不存在对应日期(如2月无30号),可根据业务需求选择跳过或者取当月最后一天
  • 时间范围查询:先拉取所有不重复且时间落在查询范围内的事件,再拉取重复规则生效的事件按规则生成对应实例,合并后返回即可
  • 如需支持更复杂的重复规则(如间隔N周/月、跳过节假日等),可直接使用Django生态内的第三方重复规则组件,无需从零手写逻辑。

内容的提问来源于stack exchange,提问作者Abdulrahman Dawoud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:45:03