diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index 2b48f09f219..55565579aee 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -380,12 +380,12 @@ def date_hierarchy(cl): # select appropriate start level date_range = cl.queryset.aggregate(first=models.Min(field_name), last=models.Max(field_name)) - if dates_or_datetimes == 'datetimes': - date_range = { - k: timezone.localtime(v) if timezone.is_aware(v) else v - for k, v in date_range.items() - } if date_range['first'] and date_range['last']: + if dates_or_datetimes == 'datetimes': + date_range = { + k: timezone.localtime(v) if timezone.is_aware(v) else v + for k, v in date_range.items() + } if date_range['first'].year == date_range['last'].year: year_lookup = date_range['first'].year if date_range['first'].month == date_range['last'].month: diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py index ada1e886ae0..e9723a9a7c1 100644 --- a/tests/admin_views/tests.py +++ b/tests/admin_views/tests.py @@ -969,6 +969,11 @@ class AdminViewBasicTest(AdminViewBasicTestCase): self.assertEqual(response.context['site_url'], '/my-site-url/') self.assertContains(response, 'View site') + def test_date_hierarchy_empty_queryset(self): + self.assertIs(Question.objects.exists(), False) + response = self.client.get(reverse('admin:admin_views_answer2_changelist')) + self.assertEqual(response.status_code, 200) + @override_settings(TIME_ZONE='America/Sao_Paulo', USE_TZ=True) def test_date_hierarchy_timezone_dst(self): # This datetime doesn't exist in this timezone due to DST.