Prevent creation of new model object if another one was created less than 24 hours ago in Django

huangapple go评论61阅读模式
英文:

Prevent creation of new model object if another one was created less than 24 hours ago in Django

问题

models.py

class Venue(models.Model):
    name = models.CharField(verbose_name="Name", max_length=100, blank=True)

class RuleModel(models.Model):
    venue = models.ForeignKey(Venue, null=True, blank=True, on_delete=models.CASCADE)
    points = models.IntegerField(verbose_name="loyalty_points_rule", null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    timeframe = models.IntegerField(verbose_name='timeframe during which more points cannot be reclaimed', null=True, blank=True)

class MyModel(models.Model):
    user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE)
    venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE)
    add_points = models.DecimalField(name='add_points', null=True, blank=True, default=0, decimal_places=2, max_digits=50)
    qr_code_venue = models.ImageField(upload_to='qr_codes_venue', blank=True)
    timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True)

    def save(self, *args, **kwargs):
        rule_model = RuleModel.objects.filter(venue=self.venue).first()
        if rule_model and rule_model.timeframe:
            try:
                date_from = datetime.datetime.now() - datetime.timedelta(days=rule_model.timeframe)
                MyModel.objects.get(venue=self.venue, timestamp__gte=date_from)
                # raise some save error
            except MyModel.DoesNotExist:
                super(MyModel, self).save(*args, **kwargs)
        else:
            super(MyModel, self).save(*args, **kwargs)
英文:

I am trying to prevent a model object to be created, if another one was created say less than 24 hours ago.

There is a trick however. This rule does not apply to ALL model objects and will dependent on a set of rule laid out in a different model.

To be more specific, if Venue_1 has a RuleModel set to 1, then when creating a new MyModel object the database would check if a previous MyModel object had been created within less than 1 day ago. If true then new MyModel object is not saved, if false MyModel object is saved.

However if Venue_2 does not have any rule, then MyModel objects can be created without any time restrictions.

After some research on this forum, it looks like I need to override the save function in the model.

This is not working at present. Not error message.

models.py

class Venue(models.Model):
    name = models.CharField(verbose_name="Name",max_length=100, blank=True)

class RuleModel(models.Model):
    venue = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE)
    points = models.IntegerField(verbose_name="loylaty_points_rule", null = True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    timeframe = models.IntegerField(verbose_name='timeframe during which more points cannot be reclaimed', null=True, blank=True)

class MyModel(models.Model):
    user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE)
    venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE)
    add_points = models.DecimalField(name = 'add_points', null = True, blank=True, default=0, decimal_places=2, max_digits=50)
    qr_code_venue = models.ImageField(upload_to='qr_codes_venue', blank=True)
    timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    
    def save(self, *args, **kwargs):
        rule_model = RuleModel()
        for rulemodel in rule_model:
            if rulemodel.timeframe:
                try:
                    date_from = datetime.datetime.now() - datetime.timedelta(days=rulemodel.timeframe)
                    MyModel.objects.get(timestamp__gte=date_from)
                    #raise some save error
                except MyModel.DoesNotExist:
                    super(MyModel,self).save(*args,**kwargs) 

答案1

得分: 1

def save(self, *args, **kwargs):
    if not self.pk:
       last_obj = YourModelName.objects.last()
       if last_obj and timezone.now() - last_obj.created_at < timezone.timedelta(hours=24):
          raise ValidationError('您的消息')
    super().save(*args, **kwargs)

注意: 您的模型必须有 created_atupdated_at 字段。

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
英文:
def save(self, *args, **kwargs):
    if not self.pk:
       last_obj = YourModelName.objects.last()
       if last_obj and timezone.now() - last_obj.created_at &lt; timezone.timedelta(hours=24):
          raise ValidationError(&#39;Your Message&#39;)
    super().save(*args, **kwargs)

Note: Your Model must have created_at or updated_at fields

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

huangapple
  • 本文由 发表于 2023年3月23日 12:11:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75819187.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定