From 42444fbf8da1a6f5a38897c4aa8e21294ff90a1b Mon Sep 17 00:00:00 2001
From: Frank Sauerburger <frank@sauerburger.com>
Date: Wed, 13 Jan 2021 10:49:03 +0100
Subject: [PATCH] Use custom manager for Plot to defer uhepp loading

---
 .../management/commands/fill_plot_title.py         | 13 +++++++++++++
 uhepp_org/uhepp_vault/models.py                    | 14 ++++++++++++++
 2 files changed, 27 insertions(+)
 create mode 100644 uhepp_org/uhepp_vault/management/commands/fill_plot_title.py

diff --git a/uhepp_org/uhepp_vault/management/commands/fill_plot_title.py b/uhepp_org/uhepp_vault/management/commands/fill_plot_title.py
new file mode 100644
index 0000000..08fe840
--- /dev/null
+++ b/uhepp_org/uhepp_vault/management/commands/fill_plot_title.py
@@ -0,0 +1,13 @@
+
+from django.core.management.base import BaseCommand
+from uhepp_vault.models import Plot
+
+
+class Command(BaseCommand):
+    def handle(self, *args, **options):
+        print("Setting title fields")
+        for plot in Plot.objects.filter(title__isnull=True):
+            print(f"  Update {plot.uuid}")
+            plot.title = str(plot)
+            plot.save()
+        print("Done")
diff --git a/uhepp_org/uhepp_vault/models.py b/uhepp_org/uhepp_vault/models.py
index c57d48a..7c78ba3 100644
--- a/uhepp_org/uhepp_vault/models.py
+++ b/uhepp_org/uhepp_vault/models.py
@@ -40,12 +40,21 @@ class Collection(models.Model):
     def __str__(self):
         return f"{self.owner}: {self.title}"
 
+class LazyPlotManger(models.Manager):
+    use_for_related_fields = True
+
+    def get_queryset(self, *args, **kwargs):
+        return super() \
+            .get_queryset(*args, **kwargs) \
+            .defer("uhepp")
+
 class Plot(models.Model):
     """Database record of a uhepp compliant plot"""
     uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
     uhepp = models.JSONField()
     ui_view_count = models.IntegerField(default=0)
     api_view_count = models.IntegerField(default=0)
+    title = models.TextField(null=True, blank=True)
 
     collection = models.ForeignKey(
         Collection,
@@ -53,6 +62,8 @@ class Plot(models.Model):
         related_name='plots'
     )
 
+    objects = LazyPlotManger()
+
     def view_count(self):
         # Plus 1 since increments are not updated
         return self.api_view_count + self.ui_view_count + 1
@@ -70,6 +81,9 @@ class Plot(models.Model):
         )
 
     def __str__(self):
+        if self.title:
+            return self.title
+
         try:
             metadata = self.uhepp.get("metadata", {})
             filename = metadata.get("filename")
-- 
GitLab