Alphabet filter in Django admin Django 05.06.2015

Short snippet: how to add alphabet filter in Django admin.

Suppose we have a model like this

from django.db import models

class Animal(models.Model):
    name = models.CharField(u'name', max_length=255)

and admin file like this

from django.contrib import admin

class AlphabetFilter(admin.SimpleListFilter):
    title = 'alphabet'
    parameter_name = 'alphabet'

    def lookups(self, request, model_admin):
        abc = list(string.ascii_lowercase)
        return ((c.upper(), c.upper()) for c in abc)

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(name__startswith=self.value())


class AnimalAdmin(admin.ModelAdmin):
    list_display = ['name',]
    list_filter = (AlphabetFilter,)
admin.site.register(Animal, AnimalAdmin)