admin: songs: Add a filter on reportnote count

This filter allows the admin to list only the songs that have a
report note that needs to be resolved.
This commit is contained in:
Daan Sprenkels
2020-06-15 16:14:10 +02:00
parent 4a1df11b40
commit 416fb3e5a9

View File

@ -1,4 +1,5 @@
from django.contrib import admin from django.contrib import admin
from django.db.models import Count
from .models import ReportNote, Song from .models import ReportNote, Song
@ -7,15 +8,37 @@ class ReportNoteInline(admin.StackedInline):
model = ReportNote model = ReportNote
extra = 0 extra = 0
class SongHasReportNoteFilter(admin.SimpleListFilter):
title = 'report notes'
parameter_name = 'reportnotes'
def lookups(self, request, model_admin):
return (
('yes', 'yes'),
('no', 'no'),
)
def queryset(self, request, queryset):
queryset = queryset.annotate(num_reports=Count('reportnote'))
if self.value() == 'yes':
return queryset.exclude(num_reports=0)
if self.value() == 'no':
return queryset.filter(num_reports=0)
return queryset
@admin.register(Song) @admin.register(Song)
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
list_display = ('artist', 'title', 'user_name', 'reports') list_display = ('artist', 'title', 'user_name', 'reports')
list_display_links = ('artist', 'title')
list_filter = (SongHasReportNoteFilter,)
search_fields = ('artist', 'title', 'user__name') search_fields = ('artist', 'title', 'user__name')
inlines = [ReportNoteInline] inlines = [ReportNoteInline]
@staticmethod @staticmethod
def reports(song): def reports(song):
return ReportNote.objects.filter(song=song).count() # num_reports is annotated by SongHasReportNoteFilter
return song.num_reports
@staticmethod @staticmethod
def user_name(song): def user_name(song):