Skip to content

Commit

Permalink
move manipluation of list_display and list_filter
Browse files Browse the repository at this point in the history
move the manipulation of list_display and list_filter to overridden get_list_*
methods. The ModelAdmin seems to get instantiated when executing management
commands and the user_count query throws an exception table doesn't exist if
the database hasn't been created. This means that it's not possible to actually
create the database.
  • Loading branch information
adsworth committed Aug 31, 2018
1 parent 50d60bf commit 1d98625
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 1d98625

Please sign in to comment.