Skip to content

Instantly share code, notes, and snippets.

@inoshiro
Last active January 17, 2017 12:08
Show Gist options
  • Save inoshiro/5696804 to your computer and use it in GitHub Desktop.
Save inoshiro/5696804 to your computer and use it in GitHub Desktop.
Djangoのadminのカスタマイズ例(search/sort/pagination)
from django.contrib import admin
from .models import Memo
class MemoAdmin(admin.ModelAdmin):
list_per_page = 5
list_display = ['username', 'title']
search_fields = ['user__username']
def queryset(self, request):
qs = super(MemoAdmin, self).queryset(request)
qs = qs.select_related('user__username')
return qs
def username(self, obj):
return obj.user.username
username.admin_order_field = 'user__username'
admin.site.register(Memo, MemoAdmin)
from django.db import models
from django.contrib.auth.models import User
class Memo(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=128)
body = models.TextField()
@inoshiro
Copy link
Author

inoshiro commented Jun 3, 2013

select_relatedで外部テーブルのカラムを予め指定することで、レコードごとにクエリ発行しないで済む

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment