[PATCH v2 1/4] models: Make use of aggregates

Stephen Finucane stephen at that.guru
Thu Oct 20 18:28:53 AEDT 2016


We're well past Django 1.1 now, so resolve a TODO to use aggregate
support introduced in this version. As part of this change, replace
the use of 'count' to check for presence of matching objects with
'exists'.

Signed-off-by: Stephen Finucane <stephen at that.guru>
---
 patchwork/models.py | 20 +++++++-------------
 1 file changed, 7 insertions(+), 13 deletions(-)

diff --git a/patchwork/models.py b/patchwork/models.py
index f8759a5..6f3257f 100644
--- a/patchwork/models.py
+++ b/patchwork/models.py
@@ -577,25 +577,19 @@ class Bundle(models.Model):
         return self.patches.order_by('bundlepatch__order')
 
     def append_patch(self, patch):
-        # todo: use the aggregate queries in django 1.1
-        orders = BundlePatch.objects.filter(bundle=self).order_by('-order') \
-            .values('order')
+        orders = BundlePatch.objects.filter(bundle=self).aggregate(
+            models.Max('order'))
 
-        if len(orders) > 0:
-            max_order = orders[0]['order']
+        if orders and orders['order__max']:
+            max_order = orders['order__max']
         else:
             max_order = 0
 
-        # see if the patch is already in this bundle
-        if BundlePatch.objects.filter(bundle=self,
-                                      patch=patch).count():
+        if BundlePatch.objects.filter(bundle=self, patch=patch).exists():
             return
 
-        bp = BundlePatch.objects.create(bundle=self, patch=patch,
-                                        order=max_order + 1)
-        bp.save()
-
-        return bp
+        return BundlePatch.objects.create(bundle=self, patch=patch,
+                                          order=max_order + 1)
 
     def public_url(self):
         if not self.public:
-- 
2.7.4



More information about the Patchwork mailing list