From 1be125fc1d9f0aa9193c80eac57603bf5a3dd9fe Mon Sep 17 00:00:00 2001 From: Mouse Reeve Date: Wed, 11 Aug 2021 11:19:06 -0700 Subject: [PATCH] Adds database constraint for readthrough dates --- .../migrations/0083_auto_20210811_1817.py | 27 +++++++++++++++++++ bookwyrm/models/readthrough.py | 15 +++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 bookwyrm/migrations/0083_auto_20210811_1817.py diff --git a/bookwyrm/migrations/0083_auto_20210811_1817.py b/bookwyrm/migrations/0083_auto_20210811_1817.py new file mode 100644 index 000000000..2abc88b0a --- /dev/null +++ b/bookwyrm/migrations/0083_auto_20210811_1817.py @@ -0,0 +1,27 @@ +# Generated by Django 3.2.4 on 2021-08-11 18:17 + +from django.db import migrations, models +import django.db.models.expressions + + +class Migration(migrations.Migration): + + dependencies = [ + ("bookwyrm", "0082_auto_20210806_2324"), + ] + + operations = [ + migrations.AlterModelOptions( + name="readthrough", + options={"ordering": ("-start_date",)}, + ), + migrations.AddConstraint( + model_name="readthrough", + constraint=models.CheckConstraint( + check=models.Q( + ("finish_date__gte", django.db.models.expressions.F("start_date")) + ), + name="chronology", + ), + ), + ] diff --git a/bookwyrm/models/readthrough.py b/bookwyrm/models/readthrough.py index df341c8b2..343d3c115 100644 --- a/bookwyrm/models/readthrough.py +++ b/bookwyrm/models/readthrough.py @@ -1,7 +1,8 @@ """ progress in a book """ -from django.db import models -from django.utils import timezone from django.core import validators +from django.db import models +from django.db.models import F, Q +from django.utils import timezone from .base_model import BookWyrmModel @@ -41,6 +42,16 @@ class ReadThrough(BookWyrmModel): ) return None + class Meta: + """Don't let readthroughs end before they start""" + + constraints = [ + models.CheckConstraint( + check=Q(finish_date__gte=F("start_date")), name="chronology" + ) + ] + ordering = ("-start_date",) + class ProgressUpdate(BookWyrmModel): """Store progress through a book in the database."""