Skip to content

Instantly share code, notes, and snippets.

@moritz89
Created October 2, 2020 01:26
Show Gist options
  • Save moritz89/0a3622f67ff804b729c64929142a1836 to your computer and use it in GitHub Desktop.
Save moritz89/0a3622f67ff804b729c64929142a1836 to your computer and use it in GitHub Desktop.
class Sensor(models.Model):
name = models.CharField(max_length=50)
class SensorReading(models.Model):
time = models.DateTimeField(primary_key=True, default=datetime.now)
sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE)
value = models.FloatField()
def save(self, *args, **kwargs):
self.save_and_smear_timestamp(*args, **kwargs)
def save_and_smear_timestamp(self, *args, **kwargs):
"""Recursivly try to save by incrementing the timestamp on duplicate error"""
try:
super().save(*args, **kwargs)
except IntegrityError as exception:
# Only handle the error:
# psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "1_1_farms_sensorreading_pkey"
# DETAIL: Key ("time")=(2020-10-01 22:33:52.507782+00) already exists.
if all (k in exception.args[0] for k in ("Key","time", "already exists")):
# Increment the timestamp by 1 µs and try again
self.time = str(parse_datetime(self.time) + timedelta(microseconds=1))
self.save_and_smear_timestamp(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment