1. from customers.models import *
  2. from django.db.models.sql.datastructures import Date
  3. from django.db.models import *
  4. from django.db.models.fields import DateField
  5. class AggregateDate(object):
  6. def __init__(self, lookup, kind, **extra):
  7. self.lookup = lookup
  8. self.kind = kind
  9. self.extra = extra
  10. def _default_alias(self):
  11. return '%s__%s' % (self.lookup, self.kind)
  12. default_alias = property(_default_alias)
  13. def add_to_query(self, query, alias, col, source, is_summary):
  14. klass = Date
  15. aggregate = klass(col, self.kind, source=source, is_summary=is_summary, **self.extra)
  16. query.add_filter(("%s__isnull" % self.lookup, False))
  17. query.aggregates[alias] = aggregate
  18. class Date(object):
  19. is_ordinal = False
  20. is_computed = False
  21. def __init__(self, col, lookup_type, source=None, is_summary=None, **extra):
  22. self.col = col
  23. self.lookup_type = lookup_type
  24. self.source = source
  25. self.is_summary = is_summary
  26. self.extra = extra
  27. self.field = DateField() # May need to change
  28. def relabeled_clone(self, change_map):
  29. return self.__class__((change_map.get(self.col[0], self.col[0]), self.col[1]))
  30. def as_sql(self, qn, connection):
  31. if isinstance(self.col, (list, tuple)):
  32. col = '%s.%s' % tuple([qn(c) for c in self.col])
  33. else:
  34. col = self.col
  35. return connection.ops.date_trunc_sql(self.lookup_type, col), []
  36. PersonCustomer.objects.all().annotate(day=AggregateDate("edited", "year")).values("day")
  1. More ...
 
 

90

 

1647

Agregate by Date (multi-db)

-

PasteBin

Size
1.6 KB
Created
타입
text/x-python
Public Domain (PD)
Please log in to leave a comment!