I'm making a generic template that will be displaying a list of objects from a queryset:
{% for o in objects %}
{{ o.name }}
{% endfor %}
I want to be able to use the template in multiple situations, where different sorts of filtering and ordering need to be done. I have created a view function for this:
def display_objects(request, filters, orders, template_name):
objects = Object.objects.all()
for filter in filters:
objects = objects.filter(('%s__%s' % (filter['field'], filter['relationship']), filter['value']))
for order in orders:
objects = objects.order_by('-' if 'descending' in order else '' + order['field'])
# render objects to template with context
pass
I'm not sure if what I have done so far will even work, but I've run into an issue. I don't know if it's feasible to filter the query set by a parameter captured in the URL with my current function.
For example, if I wanted to display objects pertaining to a certain user I would do something like:
(r'^user/(?P<account_username>[^/]+)/$', display_objects, dict(filters=[{'field':'account__username','relationship':'iexact','value':account_username}], orders=[{'field':'foobar'}], template_name='user.html'))
Obviously, account_username isn't a defined field until the URL is parsed and dispatched to the display_objects function. It would be easy enough to make a view function that takes an account_username parameter, but I want to be able to use the function for displaying other object query sets that will be filtered with different captured parameters.
Is there some way I can pass captured URL parameters to a view function to dynamically filter or order a query set to be displayed?