以下是模型示例:
HList
这是锻炼的Admin类:
class Books(models.Model):
...
class Chapter(models.Model):
...
book = models.ForeignKey('Books')
class Exercise(models.Model):
...
book = models.ForeignKey('Books')
chapter = models.ForeignKey('Chapter')
我现在为class ExerciseAdmin(admin.ModelAdmin):
...
list_filter = (('book',admin.RelatedOnlyFieldListFilter),('chapter',admin.RelatedOnlyFieldListFilter))
admin.site.register(Exercise, ExerciseAdmin)
设置了过滤器book
和chapter
。当我点击过滤器exercise
中的book
时,它会相应地显示所选book
的所有exercises
。但是在过滤器book
列表中,它仍会显示所有chapter
的所有chapters
。
有没有办法只在过滤器books
中显示我在第一个过滤器chapter
中选择的chapters
的{{1}}?怎么样?
答案 0 :(得分:0)
您是否通过管理员文档https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter使用SimpleListFilter
查看了此内容此线程中的示例... Creating Custom Filters for list_filter in Django Admin
猜猜......
from django.contrib.admin import SimpleListFilter
class ChapterFilter(SimpleListFilter):
title = 'chapter'
parameter_name = 'chapter'
def lookups(self, request, model_admin):
chapters = set([c.book for c in model_admin.model.objects.all()])
return [(b.id, b.name) for b in chapters]
def queryset(self, request, queryset):
if self.value():
return queryset.filter(book__id__exact=self.value())
class BookAdmin(ModelAdmin):
list_filter = (('book',admin.RelatedOnlyFieldListFilter), (ChapterFilter))
答案 1 :(得分:0)
我不确定这是否是最好的方法,但是在这里我使用管理面板中的网址的GET参数来获取图书的ID然后我可以选择相应的章节。它有效!
class ChapterFilter(admin.SimpleListFilter):
title = 'chapter'
parameter_name = 'chapter'
def lookups(self, request, model_admin):
if 'book__id__exact' in request.GET:
id = request.GET['book__id__exact']
chapters = set([c.chapter for c in model_admin.model.objects.all().filter(book=id)])
else:
chapters = set([c.chapter for c in model_admin.model.objects.all()])
return [(b.id, b.titre) for b in chapters]
def queryset(self, request, queryset):
if self.value():
return queryset.filter(chapter__id__exact=self.value())
class ExerciseAdmin(admin.ModelAdmin):
list_filter = (('book',admin.RelatedOnlyFieldListFilter), (ChapterFilter))