Models.py
class Bug(models.Model):
title = models.CharField(max_length=200)
creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator")
lead = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.SET_NULL,
related_name="lead")
contributors = models.ManyToManyField(User, default=None, blank=True, null=True,
related_name="contributors")
project = models.ForeignKey(Project, null=True, on_delete=models.CASCADE)
created_at = models.DateTimeField(default=timezone.now)
last_modified = models.DateTimeField(auto_now=True)
status = models.ForeignKey(Status, on_delete=models.CASCADE, default=0)
description = models.TextField()
class Meta:
constraints = [
models.CheckConstraint(
check=(
models.Q(
abs(datetime.now().microsecond - created_at.microsecond) > 10
)
),
name="%(app_label)s_%(class)s_exact_date",
)
]
When I attempt to run tests on it I get the following error:
NameError: name 'created_at' is not defined
I am trying to enforce a constraint that the created_at
date for a bug be either exactly the time it was created or within some tight bound of the time that it was created. I wish to enforce it at the database level because I'm trying to secure the data not only from form entry (in which case I could just add a validator or add editable=false on the field), but also from any other attempt to save incorrect data to the database through the ORM. I'm also using constraints rather than validators because I don't want to have to override multiple functions (save(), update(), etc).
System information: Python v3.9.0, Django v3.1.4