Skip to content

Commit

Permalink
Merge pull request #1 from adsworth/fix_startup_when_no_db
Browse files Browse the repository at this point in the history
move manipluation of list_display and list_filter
  • Loading branch information
jedie authored Sep 2, 2018
2 parents 4327794 + 1d98625 commit 50ed2bb
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions for_runners/admin/gpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from django.http import HttpResponseRedirect
from django.template.loader import render_to_string
from django.template.response import TemplateResponse
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.views import generic
Expand Down Expand Up @@ -456,23 +457,6 @@ def __init__(self, *args, **kwargs):
"creator",
]

# FIXME: This will only evaluate on start-up !

qs = GpxModel.objects.all().only("tracked_by").order_by("tracked_by")

try:
user_count = qs.distinct("tracked_by").count()
except (NotImplementedError, NotSupportedError):
# e.g.: sqlite has no distinct :(
qs = qs.values_list("tracked_by__id", flat=True)
user_count = len(set(qs))

print("count:", user_count)
if user_count <= 1:
# display user names only if there are tracks from more than one user ;)
self.list_display.remove("tracked_by")
self.list_filter.remove("tracked_by")

search_fields = (
"full_start_address",
"full_finish_address",
Expand Down Expand Up @@ -591,6 +575,39 @@ def get_urls(self):
] + urls
return urls


@cached_property
def user_count(self):
qs = GpxModel.objects.all().only("tracked_by").order_by("tracked_by")

try:
user_count = qs.distinct("tracked_by").count()
except (NotImplementedError, NotSupportedError):
# e.g.: sqlite has no distinct :(
qs = qs.values_list("tracked_by__id", flat=True)
user_count = len(set(qs))

return user_count


def get_list_display(self, request):
list_display = super(GpxModelAdmin, self).get_list_display(request).copy()

if self.user_count <= 1 and 'tracked_by' in list_display:
list_display.remove("tracked_by")

return list_display


def get_list_filter(self, request):
list_filter = super(GpxModelAdmin, self).get_list_filter(request).copy()

if self.user_count <= 1 and 'tracked_by' in list_filter:
list_filter.remove("tracked_by")

return list_filter


def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
Expand Down

0 comments on commit 50ed2bb

Please sign in to comment.