Last active
January 17, 2017 12:08
-
-
Save inoshiro/5696804 to your computer and use it in GitHub Desktop.
Djangoのadminのカスタマイズ例(search/sort/pagination)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
select_relatedで外部テーブルのカラムを予め指定することで、レコードごとにクエリ発行しないで済む