Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Customizing the Django Admin Customizing the List View Building Custom Filters

Guy Scorpion
Guy Scorpion
11,053 Points

How would I create a custom filter based on the created date of an item?

The video shows how to create a filter using years but it doesn't get this info from entries in the database.

Method shown in the video:

    def lookups(self, request, model_admin):
        return (
            ('2015', '2015'),
            ('2016', '2016'),
        )

    def queryset(self, request, queryset):
        years = [2015, 2016]
        for year in years:
            if self.value() == str(year):
                return queryset.filter(created_at__gte=date(year, 1, 1),
                                       created_at__lte=date(year, 12, 31))

How would I go about checking for entries, retrieving the year they were created, then using that as the lookup?

Steven Parker
Steven Parker
231,248 Points

:mailbox_with_mail: Hi, I got your message.

But I don't know Django (yet). I'll have to leave this one for someone else.

:bulb: The resource recommendation mechanism could be improved by checking for people who have answered questions on a particular topic before and/or have completed courses on those topics. Clearly, it needs to be more specific about the "topic" than just the language.

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Guy,

You've probably figured this out for yourself by now, but for anyone else wondering the same thing. Here is a simple way you could achieve what you're looking for.

(I'm just replacing your lookups method, everything else is the same):

def lookups(self, request, model_admin):

        # 1. make a queryset of all the records in the DB
        objs = model_admin.model.objects.all()

        # 2. get just the created_at field
        dates = objs.values_list('created_at', flat=True)

        # 3. get just the years
        years = [d.year for d in dates]

        # 4. get the unique years
        years = set(years)

        # 5. sort it
        years = sorted(years)

        # 6. format as a valid lookup (the example is a tuple of tuples, but a list of tuples is valid too)
        lookup = [(y, y) for y in years]

        return lookup

Cheers,

Alex