61864

Filtering Objects in Class based view Django using Query parameters?

Question:

I am using Class-based Generic views Listview for listing all objects.

My views.py:

class PostsList(ListView): model = Post template_name = "index.html"

My Urls.py:

urlpatterns = [ url(r'^$',PostsList.as_view(), name = "home"), ]

This gives me a list of all the posts. Now I want to <strong>filter/sort</strong> posts based on certain fields of Post Model, say price. Do I need to write this myself? If yes Which method of PostsLists class do I override ? def get, def get_context ?

I see the get method for Listview defined as below. In it can I pass URL query-parameters as **kwargs directly or I have to overwrite the below method in my class.

def get(self, request, *args, **kwargs): ....

Answer1:

You can override the get_queryset method:

Keep a mapping of all the parameters that you can get in the url kwargs.

def get_queryset(self): queryset = Post.objects.all() if self.request.GET.get('price'): queryset = queryset.filter(price=self.request.GET.get('price')) return queryset

Answer2:

When using Django's class based views, avoid overriding get() or post() if possible. These methods do a lot, and if you override them, you may have to duplicate a lot of the built in functionality. There are normally more specific methods that you can override.

In your case, you can filter the queryset dynamically with the get_queryset method. You can access GET parameters with self.request.GET. For example:

class PostsList(ListView): model = Post def get_queryset(self): """Filter by price if it is provided in GET parameters""" queryset = super(PostsList, self).get_queryset() if 'price' in self.request.GET: queryset = queryset.filter(price=self.request.GET['price']) return queryset

If your url captures arguments, you can access them with self.args (positional) and self.kwargs (name based).

See the docs on <a href="https://docs.djangoproject.com/en/1.8/topics/class-based-views/generic-display/#dynamic-filtering" rel="nofollow">dynamic filtering</a> for more info.

Recommend

  • django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship usin
  • fix_location_header in Django causes wrong redirection to LOGIN_URL
  • Django--URL Caching Failing for Class Based Views
  • Django class view: __init__
  • Dispose not working as expected in DirectorySearcher
  • Fluid video height
  • Weird LEFT OUTER JOIN on Includes eager loading of rails 3
  • Installing Perl6 and Panda on Ubuntu 15.10. Problems with bootstrap.pl
  • Can my PDF ping my server when it is opened?
  • Can't remove headers after they are sent
  • Grails calculated field in SQL
  • Webgrid not refreshing after delete MVC
  • How can I sort a a table with VBA with given text condition?
  • Android full screen on only one activity?
  • Is it possible to access block's scope in method?
  • How can I send an e-mail from a vbs script
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Spring security and special characters
  • Accessing IRQ description array within a module and displaying action names
  • Can Jackson SerializationFeature be overridden per field or class?
  • How to add date and time under each post in guestbook in google app engine
  • JSON with duplicate key names losing information when parsed
  • Return words with double consecutive letters
  • Circular dependency while pushing http interceptor
  • retrieve vertices with no linked edge in arangodb
  • AngularJs get employee from factory
  • How to set the response of a form post action to a iframe source?
  • how does django model after text[] in postgresql [duplicate]
  • Change div Background jquery
  • Turn off referential integrity in Derby? is it possible?
  • Linking SubReports Without LinkChild/LinkMaster
  • Add sale price programmatically to product variations
  • MATLAB: Piecewise function in curve fitting toolbox using fittype
  • Does armcc optimizes non-volatile variables with -O0?
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app
  • Python/Django TangoWithDjango Models and Databases
  • How do I use LINQ to get all the Items that have a particular SubItem?