Search by function returns in Django Admin
2021. 7. 27. 03:38
장고를 사용하다 보면 search_fields 를 사용할 일이 생기는데, 이때 여러 fields 간의 결합된 것들 중 검색하고 싶을 때는 어떻게 해야하는지 단서를 제공할 수 있는 글이다.
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
User = get_user_model()
class CustomUserAdmin(UserAdmin):
search_fields = ['username']
# search by username
def get_search_results(self, request, queryset, search_term):
# default
queryset, may_have_duplicates = super().get_search_results(request, queryset, search_term)
search_term = request.GET.get('q')
# print('[ DEBUG ] search_term :', search_term)
if not search_term:
return queryset, may_have_duplicates
return User.objects.filter(username__contains=search_term), may_have_duplicates
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
Model Admin에서 get_search_results() 를 override 하면 된다.
'Codes > Python' 카테고리의 다른 글
How does Django execute SQL Query? (Korean version) (1) | 2022.12.16 |
---|---|
Add middleware which loads JSON body in Django Python (0) | 2020.09.09 |
Django How to delete superuser (0) | 2020.08.13 |
Django Parsing Json in Function based view (0) | 2020.08.13 |
Django Customizing Default User Model (0) | 2020.08.12 |