Skip to content

Commit a567f03

Browse files
committed
admin: prefetch related fields
1 parent 335530d commit a567f03

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

pinax/stripe/admin.py

+22
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from django.contrib import admin
2+
from django.contrib.admin.views.main import ChangeList
23
from django.contrib.auth import get_user_model
34
from django.db.models import Count, Q
45

@@ -105,8 +106,28 @@ def queryset(self, request, queryset):
105106
return queryset.all()
106107

107108

109+
class PrefetchingChangeList(ChangeList):
110+
"""A custom changelist to prefetch related fields."""
111+
def get_queryset(self, request):
112+
qs = super(PrefetchingChangeList, self).get_queryset(request)
113+
114+
if subscription_status in self.list_display:
115+
qs = qs.prefetch_related('subscription_set')
116+
if 'customer' in self.list_display:
117+
qs = qs.prefetch_related('customer')
118+
if 'user' in self.list_display:
119+
qs = qs.prefetch_related('user')
120+
return qs
121+
122+
123+
class ModelAdmin(admin.ModelAdmin):
124+
def get_changelist(self, request, **kwargs):
125+
return PrefetchingChangeList
126+
127+
108128
admin.site.register(
109129
Charge,
130+
admin_class=ModelAdmin,
110131
list_display=[
111132
"stripe_id",
112133
"customer",
@@ -202,6 +223,7 @@ def subscription_status(obj):
202223

203224
admin.site.register(
204225
Customer,
226+
admin_class=ModelAdmin,
205227
raw_id_fields=["user"],
206228
list_display=[
207229
"stripe_id",

pinax/stripe/tests/test_admin.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import datetime
22

3+
import django
34
from django.contrib.auth import get_user_model
45
from django.test import Client, TestCase
56
from django.utils import timezone
@@ -99,8 +100,16 @@ def setUp(self):
99100
def test_customer_admin(self):
100101
"""Make sure we get good responses for all filter options"""
101102
url = reverse("admin:pinax_stripe_customer_changelist")
102-
response = self.client.get(url)
103-
self.assertEqual(response.status_code, 200)
103+
104+
# Django 1.10 has the following query twice:
105+
# SELECT COUNT(*) AS "__count" FROM "pinax_stripe_customer"
106+
# (since https://github.com/django/django/commit/5fa7b592b3f)
107+
# We might want to test for "num < 10" here instead, and/or compare the
108+
# number to be equal with X and X+1 customers
109+
num = 8 if django.VERSION >= (1, 10) else 7
110+
with self.assertNumQueries(num):
111+
response = self.client.get(url)
112+
self.assertEqual(response.status_code, 200)
104113

105114
response = self.client.get(url + "?sub_status=active")
106115
self.assertEqual(response.status_code, 200)

0 commit comments

Comments
 (0)