简体   繁体   中英

If it possible to filter out names of objects returned in Django Admin

For my Django CMS Admin I would like to prevent it returning a specific object to the CMS. What is the best way to do this?

I would like to do something like

class MyModuleAdmin(admin.ModelAdmin):
    list_display = ['name']
    list_filter = ('my_module__name__is_not=moduleidontwant',)

You can simply overload get_queryset admin function and filter out items you do not want:

class MyModuleAdmin(admin.ModelAdmin):
    list_display = ['name']

    def get_queryset(self, request):
        queryset = super(MyModuleAdmin, self).get_queryset(request)
        return queryset.exclude(name='moduleidontwant')
# custom_filters.py
from django.contrib.admin import SimpleListFilter

class testFilter(SimpleListFilter):
    """ This filter is being used in django admin panel in specified model."""
    title = 'Title of you field'
    parameter_name = 'field_name'
    
    def queryset(self, request, queryset):
       if not self.value():
           return queryset
       else:
           return queryset.filter(my_module__name__is_not='moduleidontwant') #add your filter here.

Add this testFilter in your list_filter in admin.py file.

# admin.py
from django.contrib import admin
from .models import *
from .custom_filters import testFilter

class MyModuleAdmin(admin.ModelAdmin):
    list_display = ['name']
    list_filter = (testFilter)

You can use this reference in case you get stuck in between https://www.dothedev.com/blog/django-admin-list_filter/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM