aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlban Gruin2017-01-27 22:48:47 +0100
committerAlban Gruin2017-01-27 22:48:47 +0100
commit5c52392e274757c09b05f62581c52a197cb51ce6 (patch)
tree2fab92af6f347db64eeb521b79ea4edd07340043
parent0253cd15092b580eecc7a711a2070920b2a90d66 (diff)
Création de différentes classes permettant d'effectuer un group by simple
* GroupedCompiler rajoute une étape à get_group_by() pour insérer de manière simple les champs à grouper * GroupedQuery rajoute une liste stockant les champs à grouper * GroupedQuerySet implémente la fonction group_by() * GroupedManager change le type de QuerySet par défaut pour GroupedQuerySet Le manager des cours se base sur GroupedManager
-rw-r--r--db.py34
-rw-r--r--models.py4
2 files changed, 31 insertions, 7 deletions
diff --git a/db.py b/db.py
index df9ceda..e75adca 100644
--- a/db.py
+++ b/db.py
@@ -1,18 +1,40 @@
+from django.db import connections
from django.db.models import Manager
from django.db.models.query import QuerySet
+from django.db.models.sql.compiler import SQLCompiler
from django.db.models.sql.query import Query
+from django.db.models.sql.where import WhereNode
+
+
+class GroupedCompiler(SQLCompiler):
+ def get_group_by(self, select, order_by):
+ result = super(GroupedCompiler, self).get_group_by(select, order_by)
+ expressions = []
+ for expr in self.query.real_group_by:
+ ref = expr if hasattr(expr, "as_sql") else self.query.resolve_ref(expr)
+ sql, params = self.compile(ref)
+ result.append((sql, params))
+
+ return result
class GroupedQuery(Query):
- def add_grouping(self, *grouping):
- if self.group_by is None:
- self.group_by = []
+ def __init__(self, model, where=WhereNode):
+ super(GroupedQuery, self).__init__(model, where)
+ self.real_group_by = []
- if isinstance(self.group_by, list):
- self.group_by.extend(grouping)
+ def add_grouping(self, *grouping):
+ self.real_group_by.extend(grouping)
def clear_grouping(self):
- self.group_by = None
+ self.real_group_by = []
+
+ def get_compiler(self, using=None, connection=None):
+ if using is None and connection is None:
+ raise ValueError("Need either using or connection")
+ if using:
+ connection = connections[using]
+ return GroupedCompiler(self, connection, using)
class GroupedQuerySet(QuerySet):
diff --git a/models.py b/models.py
index 9cb3bca..aa1cd3f 100644
--- a/models.py
+++ b/models.py
@@ -2,6 +2,8 @@ from django.db import models
from django.db.models import Q
from django.utils.text import slugify
+from .db import GroupedManager
+
import hashlib
import os
@@ -107,7 +109,7 @@ class Room(models.Model):
verbose_name_plural = "salles"
-class CourseManager(models.Manager):
+class CourseManager(GroupedManager):
def get_courses_for_group(self, group, **filters):
return self.get_queryset().filter(Q(groups__td__isnull=True) | Q(groups__td=group.td), Q(groups__tp__isnull=True) | Q(groups__tp=group.tp), groups__mention=group.mention, groups__subgroup=group.subgroup, **filters).order_by("begin")