I started using django-tables2 (which I can highly recommend from the first impression) and I m asking myself how to implement column filtering. I do not find the appropriate documentation for it, but I m sure it is somewhere out there.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
There is an easier and DRYer way to build a generic view do this:
So you can do this:
A little late answer but anyway ... I also couldn't find any appropriate documentation for column filtering. There are many methods to do it:
A. By hand: I add a form containing the fields I'd like to filter with and then I do something like this in my view:
This works very nice however it's not so DRY because it is hard coded in the view.
B. Using a SingleTableView: Another way is to add a SingleTableView that contains the form:
This is more DRY :)
C. Using SingleTableView and django_filters: This probably is the most DRY way :) Here's how to do it:
First define a filter:
(or you can add a model filter in Meta ( model = MyModel)
Now, create a SingleTableView like this
(probably there is a problem with the line f =... but I couldn't make it work otherwise.
Finally, you can call the SingleTableView from your urls.py like this
D. Using a generic class: This is an even more DRY and django-generic-class-views like way! This is actually the next step from C: Just declare your FilteredSingleTableView like this:
Now the FilteredSingleTableView has a parameter for the class of the filter so you may pass it in your urls.py among the other parameters:
So you can use FilteredSingleTableView without modifications for filtering any of your models !!
Also notice that I've now saved the filter as an instance variable and removed the repetitive code
f=filters.MyFilter(...)
that I had in C (get_table_data is called before get_context_data - if that was not always the case then we could add anget_filter
instance method that would do the trick) !Update 23/04/2016: After popular demand, I've created a simple Django project that uses the generic FilteredSingleTableView class to filter a table of books. You may find it out at: https://github.com/spapas/django_table_filtering
Update 05/07/2016: Please notice that you should use
return self.filter.qs
for theget_table_data
return in D (I've alread updated the answer with this) or else the view will take too long to render for big tables -- more info can be found on https://github.com/spapas/django_table_filtering/issues/1If you prefer to use
django_tables2.views.SingleTableMixin
in concert with Django'sListView
or a subclass thereof (rather thanSingleTableView
) I suggest the following:It has the added benefit of not being coupled to
django-tables2
(DRY FTW) meaning it can be used with genericListViews
also.