I am new to both Python and Django and would like, if possible, to follow best practices. I would like to tidy up the following code to make things easier.
I am trying to customize a view that can be accessed through several URLs that provide different parameters for which the request will be displayed and displayed.
I set the following urls:
url(r'^myrecords/$', login_required(RecordListView.as_view()), {'filter': 'all'}, name='myrecords'), url(r'^myrecords/page(?P<page>[0-9]+)/$', login_required(RecordListView.as_view()), {'filter': 'all'}, name='myrecords'), url(r'^myrecords/(?P<year>\d{4})/$', login_required(RecordListView.as_view()), {'filter': 'year'}, name='myrecords'), url(r'^myrecords/last(?P<months>[0-9]{1,2})months/$', login_required(RecordListView.as_view()), {'filter': 'month'}, name='myrecords'),
Then, in my opinion, I have something like this (there are actually several other parameters, but they should remain the same regardless of the URL entered.):
def get_queryset(self): if (self.kwargs['filter'] == 'month'): x_months_ago = (datetime.date.today() - datetime.timedelta(int(self.kwargs['months']) * 365 / 12)) queryset = Record.objects.filter(user=self.request.user, date__gte = x_months_ago.isoformat()) elif (self.kwargs['filter'] == 'year'): queryset = Record.objects.filter(user=self.request.user, date__year=self.kwargs['year']) else queryset = Record.objects.filter(user=self.request.user)
It seems very dirty to me. Anyway, can I make it cleaner? Is it possible to put filter parameters in some kind of data structure, and then just pass them to the Record.objects.filter line, and not write it all several times?
Any advice is appreciated.
Thanks.