Refactor users_stats method: use django queryset system
parent
ea6b9ae324
commit
9bc0e976ca
|
@ -12,10 +12,9 @@
|
||||||
# You should have received a copy of the GNU Affero General Public License
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
from contextlib import closing
|
|
||||||
|
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.db import connection
|
from django.db.models import Count
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
@ -37,26 +36,27 @@ def get_users_stats():
|
||||||
|
|
||||||
# Graph: users last year
|
# Graph: users last year
|
||||||
a_year_ago = timezone.now() - timedelta(days=365)
|
a_year_ago = timezone.now() - timedelta(days=365)
|
||||||
sql_query = """
|
# increments ->
|
||||||
SELECT date_trunc('week', "filtered_users"."date_joined") AS "week",
|
# SELECT date_trunc('week', "filtered_users"."date_joined") AS "week",
|
||||||
count(*)
|
# count(*)
|
||||||
FROM (SELECT *
|
# FROM (SELECT *
|
||||||
FROM "users_user"
|
# FROM "users_user"
|
||||||
WHERE "users_user"."is_active" = TRUE
|
# WHERE "users_user"."is_active" = TRUE
|
||||||
AND "users_user"."is_system" = FALSE
|
# AND "users_user"."is_system" = FALSE
|
||||||
AND "users_user"."date_joined" >= %s) AS "filtered_users"
|
# AND "users_user"."date_joined" >= %s) AS "filtered_users"
|
||||||
GROUP BY "week"
|
# GROUP BY "week"
|
||||||
ORDER BY "week";
|
# ORDER BY "week";
|
||||||
"""
|
increments = (queryset.filter(date_joined__gte=a_year_ago)
|
||||||
with closing(connection.cursor()) as cursor:
|
.extra({"week": "date_trunc('week', date_joined)"})
|
||||||
cursor.execute(sql_query, [a_year_ago])
|
.values("week")
|
||||||
rows = cursor.fetchall()
|
.order_by("week")
|
||||||
|
.annotate(count=Count("id")))
|
||||||
|
|
||||||
counts_last_year_per_week = OrderedDict()
|
counts_last_year_per_week = OrderedDict()
|
||||||
sumatory = queryset.filter(date_joined__lt=rows[0][0]).count()
|
sumatory = queryset.filter(date_joined__lt=increments[0]["week"]).count()
|
||||||
for row in rows:
|
for inc in increments:
|
||||||
sumatory += row[1]
|
sumatory += inc["count"]
|
||||||
counts_last_year_per_week[str(row[0].date())] = sumatory
|
counts_last_year_per_week[str(inc["week"].date())] = sumatory
|
||||||
|
|
||||||
stats["counts_last_year_per_week"] = counts_last_year_per_week
|
stats["counts_last_year_per_week"] = counts_last_year_per_week
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue