Django: best way to add filtering (and sorting) to (generic) class based ListView?
Asked Answered
C

1

6

Let's say I have a model like this:

class Car(models.Model):
    BRANDS = (
        ('FRD', 'Ford'),
        ('MCD', 'Mercedes'),
        ...
    )
    brand = models.CharField(max_length=3, choices=BRANDS)
    color = models.CharField(max_length=24)
    url = models.URLField()
    new = models.BooleanField(default=False)

And would like to generate a list view using class based generic views:

In urls.py

url(r'^car/list/$', CarList.as_view(), name='car_list'),

In views.py

class CarList(ListView):
    model = Car
    template_name = "list.html"
    def get_queryset(self):
        return Car.objects.all()

In list.html

{% for car in cars %}
    <tr>
        <td>{{ car.brand }}</td>
        <td>{{ car.color }}</td>
        <td>{{ car.url }}</td>
        <td>{{ car.new }}</td>
    </tr>

Now I would like to offer some options to add filters on the queryset (and sorting options per column). For example a general search box that does a %LIKE% on any column, or a selection from the brand-choices or a simple asc/desc per column.

I know the filters and sorting shall end up in the queryset (get_queryset) but this requires lots of specific work in the template and view code while I feel there should be some packages that assist in this?

Does anyone have directions for me?

Complicity answered 5/8, 2012 at 20:16 Comment(0)
K
0

Django Packages is a good place to look for, you guessed it, Django packages :-). I haven't used it before, but from a quick look you may find django-tables2 helpful. I'd guess there are others worth considering also.

Krp answered 6/8, 2012 at 4:44 Comment(1)
Thanks for the link! I was reading about django-filter(-actually-maintained) but was missing features like ordering and yes indeed also the raw html building. django-tables2 looks promising, i'm seeing lots of good things, generic views, sorting, heading, templates, etc....Complicity

© 2022 - 2024 — McMap. All rights reserved.