Django: best way to add filtering (and sorting) to a (generic) ListView class?

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 I would like to create a list view using general class-based 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 several options for adding filters to a set of queries (and sorting options per column). For example, in a general search field that does% LIKE% for any column, or a choice from brand selection or a simple asc / desc for a column.

I know that filters and sorting end in a set of queries ( get_queryset ), but it requires most of the specific work in the template and view code, while I feel that there should be some packages in it that help with this?

Do I have directions for me?

+6
source share
1 answer

Django Packages is a good place to search, you guessed it, Django packages :-). I have not used this before, but from a quick overview you can find django-tables2 . I think there are others that deserve attention.

0
source

Source: https://habr.com/ru/post/922176/


All Articles