我有两个模型。一个用户模型和一个匹配模型。用户可以在任何给定日期订阅我的服务6/12/18个月。我想限制用户每月最多10场比赛。如果用户在一个月内通过了10次匹配,我想发送一封提醒电子邮件。10场比赛的配额将在下个月重新设置。我如何做到这一点?
模型如下:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
MembershipStart = models.DateTimeField(blank=True, null=True, verbose_name="Membership Start Date")
MembershipLength = models.IntegerField(verbose_name='Length of membership in months from MembershipStart')
class Match(models.Model):
user = models.ManyToManyField(User, blank = True)
name = models.CharField(max_length = 100)
created_on = models.DateTimeField(default=timezone.now)
在Match
上附加信号将不起作用。您应该使用m2m_changed
信号:
from django.db.models.signals import m2m_changed
from django.utils import timezone
def matches_users_changed(sender, *args, **kwargs):
if kwargs['action'] == 'post_add':
instance = kwargs['instance']
added_user_ids = []
if isinstance(instance, Match):
added_user_ids += list(kwargs['pk_set'])
elif isinstance(instance, User):
added_user_ids += [instance.pk]
today = timezone.now()
for user_id in added_user_ids:
user = User.objects.get(pk=user_id)
if user.match_set.filter(created_on__year=today.year, created_on__month=today.month).count() > 10:
# Do something
m2m_changed.connect(matches_users_changed, sender=Match.user.through)
注意:action
可以有更多的值,例如"pre_add"
等,您可能会发现更有用,请参考上面链接的文档以获取适当的列表。