Created
October 2, 2020 01:26
-
-
Save moritz89/0a3622f67ff804b729c64929142a1836 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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