Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add caching table

Roland Geiderae9fb74b23ae
diff --git a/wger/core/migrations/0005_auto_20151025_2236.py b/wger/core/migrations/0005_auto_20151025_2236.py
new file mode 100644
index 000000000..b76a4072a
--- /dev/null
+++ b/wger/core/migrations/0005_auto_20151025_2236.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.core.validators
+from django.conf import settings
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ('core', '0004_auto_20150217_1914'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='UserCache',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('last_activity', models.DateField(null=True)),
+ ('user', models.OneToOneField(editable=False, to=settings.AUTH_USER_MODEL)),
+ ],
+ ),
+ migrations.AlterField(
+ model_name='userprofile',
+ name='num_days_weight_reminder',
+ field=models.IntegerField(default=0, verbose_name='Automatic reminders for weight entries', help_text='Number of days after the last weight entry (enter 0 to deactivate)', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(30)]),
+ ),
+ ]
diff --git a/wger/core/migrations/0006_auto_20151025_2237.py b/wger/core/migrations/0006_auto_20151025_2237.py
new file mode 100644
index 000000000..fbabd1c8c
--- /dev/null
+++ b/wger/core/migrations/0006_auto_20151025_2237.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+def create_usercache(apps, schema_editor):
+ '''
+ Creates a usercache table for all users
+ '''
+ User = apps.get_model("auth", "User")
+ Usercache = apps.get_model("core", "Usercache")
+ WorkoutLog = apps.get_model("manager", "WorkoutLog")
+ WorkoutSession = apps.get_model("manager", "WorkoutSession")
+
+ for user in User.objects.all():
+
+ #
+ # This is the logic of get_user_last_activity at the time this migration
+ # was created.
+ #
+ last_activity = None
+
+ # Check workout logs
+ last_log = WorkoutLog.objects.filter(user=user).order_by('date').last()
+ if last_log:
+ last_activity = last_log.date
+
+ # Check workout sessions
+ last_session = WorkoutSession.objects.filter(user=user).order_by('date').last()
+ if last_session:
+ last_session = last_session.date
+
+ # Return the last one
+ if last_session:
+ if not last_activity:
+ last_activity = last_session
+
+ if last_activity < last_session:
+ last_activity = last_session
+
+ # Create the cache entry
+ Usercache.objects.create(user=user, last_activity=last_activity)
+
+
+def delete_usercache(apps, schema_editor):
+ '''
+ Deletes the usercache table for all users
+ '''
+ Usercache = apps.get_model("core", "Usercache")
+ for cache in Usercache.objects.all():
+ cache.delete()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('core', '0005_auto_20151025_2236'),
+ ('auth', '0006_require_contenttypes_0002'),
+ ('manager', '0004_auto_20150609_1603'),
+ ]
+
+ operations = [
+ migrations.RunPython(create_usercache, delete_usercache)
+ ]
diff --git a/wger/core/models.py b/wger/core/models.py
index afbc45de6..2693feaf8 100644
--- a/wger/core/models.py
+++ b/wger/core/models.py
@@ -473,6 +473,26 @@ by the US Department of Agriculture. It is extremely complete, with around
return self
+@python_2_unicode_compatible
+class UserCache(models.Model):
+ '''
+ A table used to cache expensive queries or similar
+ '''
+
+ user = models.OneToOneField(User, editable=False)
+ '''
+ The user
+ '''
+
+ last_activity = models.DateField(null=True)
+ '''
+ The user's last activity.
+
+ Values for this entry are saved by signals as calculated by the
+ get_user_last_activity helper function.
+ '''
+
+
@python_2_unicode_compatible
class DaysOfWeek(models.Model):
'''
diff --git a/wger/core/signals.py b/wger/core/signals.py
index e0dcf204d..bd6d3239f 100644
--- a/wger/core/signals.py
+++ b/wger/core/signals.py
@@ -18,7 +18,7 @@
from django.contrib.auth.models import User
from django.db.models.signals import post_save
-from wger.core.models import UserProfile
+from wger.core.models import UserProfile, UserCache
from wger.utils.helpers import disable_for_loaddata
@@ -31,4 +31,14 @@ def create_user_profile(sender, instance, created, **kwargs):
UserProfile.objects.create(user=instance)
+@disable_for_loaddata
+def create_user_cache(sender, instance, created, **kwargs):
+ '''
+ Every new user gets a cache table
+ '''
+ if created:
+ UserCache.objects.create(user=instance)
+
+
post_save.connect(create_user_profile, sender=User)
+post_save.connect(create_user_cache, sender=User)
diff --git a/wger/gym/tests/test_user_last_activity.py b/wger/gym/tests/test_user_last_activity.py
index 2f4f60220..6704645ee 100644
--- a/wger/gym/tests/test_user_last_activity.py
+++ b/wger/gym/tests/test_user_last_activity.py
@@ -35,6 +35,7 @@ class UserLastActivityTestCase(WorkoutManagerTestCase):
log = WorkoutLog.objects.get(pk=1)
session = WorkoutSession.objects.get(pk=1)
+ self.assertEqual(user.usercache.last_activity, datetime.date(2014, 1, 30))
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 1, 30))
# Log more recent than session
@@ -42,15 +43,21 @@ class UserLastActivityTestCase(WorkoutManagerTestCase):
log.save()
session.date = datetime.date(2014, 10, 1)
session.save()
+ user = User.objects.get(username='admin')
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 10, 2))
+ self.assertEqual(user.usercache.last_activity, datetime.date(2014, 10, 2))
# Session more recent than log
log.date = datetime.date(2014, 9, 1)
log.save()
session.date = datetime.date(2014, 10, 5)
session.save()
+ user = User.objects.get(username='admin')
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 10, 5))
+ self.assertEqual(user.usercache.last_activity, datetime.date(2014, 10, 5))
# No logs, but session
WorkoutLog.objects.filter(user=user).delete()
+ user = User.objects.get(username='admin')
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 10, 5))
+ self.assertEqual(user.usercache.last_activity, datetime.date(2014, 10, 5))
diff --git a/wger/gym/views/gym.py b/wger/gym/views/gym.py
index 2b534825c..384d81f42 100644
--- a/wger/gym/views/gym.py
+++ b/wger/gym/views/gym.py
@@ -104,9 +104,9 @@ class GymUserListView(WgerPermissionMixin, ListView):
out = {'admins': [],
'members': []}
- for u in Gym.objects.get_members(self.kwargs['pk']):
+ for u in Gym.objects.get_members(self.kwargs['pk']).select_related('usercache'):
out['members'].append({'obj': u,
- 'last_log': get_user_last_activity(u)})
+ 'last_log': u.usercache.last_activity})
# admins list
for u in Gym.objects.get_admins(self.kwargs['pk']):
diff --git a/wger/manager/__init__.py b/wger/manager/__init__.py
index a915bb265..e83a37b58 100644
--- a/wger/manager/__init__.py
+++ b/wger/manager/__init__.py
@@ -19,3 +19,4 @@
from wger import get_version
VERSION = get_version()
+default_app_config = 'wger.manager.apps.ManagerConfig'
diff --git a/wger/manager/apps.py b/wger/manager/apps.py
new file mode 100644
index 000000000..8c664977b
--- /dev/null
+++ b/wger/manager/apps.py
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+from django.apps import AppConfig
+
+
+class ManagerConfig(AppConfig):
+ name = 'wger.manager'
+ verbose_name = "Manager"
+
+ def ready(self):
+ import wger.manager.signals
diff --git a/wger/manager/fixtures/test-user-data.json b/wger/manager/fixtures/test-user-data.json
index 23f4e17b8..b0015289c 100644
--- a/wger/manager/fixtures/test-user-data.json
+++ b/wger/manager/fixtures/test-user-data.json
@@ -1216,5 +1216,197 @@
"ro_access": false,
"num_days_weight_reminder":0
}
+ },
+ {
+ "pk": 1,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": "2014-01-20",
+ "user_id": 1
+ }
+ },
+ {
+ "pk": 2,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": "2014-01-30",
+ "user_id": 2
+ }
+ },
+ {
+ "pk": 3,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 3
+ }
+ },
+ {
+ "pk": 4,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 4
+ }
+ },
+ {
+ "pk": 5,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 5
+ }
+ },
+ {
+ "pk": 6,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 6
+ }
+ },
+ {
+ "pk": 7,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 7
+ }
+ },
+ {
+ "pk": 8,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 8
+ }
+ },
+ {
+ "pk": 9,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 9
+ }
+ },
+ {
+ "pk": 10,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 10
+ }
+ },
+ {
+ "pk": 11,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 11
+ }
+ },
+ {
+ "pk": 12,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 12
+ }
+ },
+ {
+ "pk": 13,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 13
+ }
+ },
+ {
+ "pk": 14,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 14
+ }
+ },
+ {
+ "pk": 15,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 15
+ }
+ },
+ {
+ "pk": 16,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 16
+ }
+ },
+ {
+ "pk": 17,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 17
+ }
+ },
+ {
+ "pk": 18,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 18
+ }
+ },
+ {
+ "pk": 19,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 19
+ }
+ },
+ {
+ "pk": 20,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 20
+ }
+ },
+ {
+ "pk": 21,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 21
+ }
+ },
+ {
+ "pk": 22,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 22
+ }
+ },
+ {
+ "pk": 23,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 23
+ }
+ },
+ {
+ "pk": 24,
+ "model": "core.usercache",
+ "fields": {
+ "last_activity": null,
+ "user_id": 24
+ }
}
]
diff --git a/wger/manager/signals.py b/wger/manager/signals.py
new file mode 100644
index 000000000..205a60fc6
--- /dev/null
+++ b/wger/manager/signals.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+
+from django.db.models.signals import post_save, post_delete
+
+from wger.gym.helpers import get_user_last_activity
+from wger.manager.models import WorkoutLog, WorkoutSession
+from wger.core.models import UserCache
+
+
+def update_activity_cache(sender, instance, **kwargs):
+ '''
+ Update the user's cached last activity date
+ '''
+
+ user = instance.user
+ user.usercache.last_activity = get_user_last_activity(user)
+ user.usercache.save()
+
+
+post_save.connect(update_activity_cache, sender=WorkoutSession)
+post_save.connect(update_activity_cache, sender=WorkoutLog)
+
+# TODO: this seems to cause problems when users are deleted
+# perhaps because of the cascading, needs to be checked
+# post_delete.connect(update_activity_cache, sender=WorkoutSession)
+# post_delete.connect(update_activity_cache, sender=WorkoutLog)
diff --git a/wger/software/templates/changelog.html b/wger/software/templates/changelog.html
index 9008040ff..b93258db7 100644
--- a/wger/software/templates/changelog.html
+++ b/wger/software/templates/changelog.html
@@ -15,6 +15,10 @@
Fix problem with datepicker
<a href="https://github.com/rolandgeider/wger/issues/192">#192</a>
</li>
+ <li>
+ Vastly reduce the number of database queries in gym member list
+ <a href="https://github.com/rolandgeider/wger/issues/144">#144</a>
+ </li>
<li>
Use hostname for submitted exercises
<a href="https://github.com/rolandgeider/wger/issues/159">#159</a>