0
To show a solution that is closer to your original code, so it only accepts a certain set of arguments (itβs a combination of the two existing answers):
def get_statistic(date__gte=None, date__lte=None, name=None):
filter_args = {'date__gte': some_date, 'date__lte': some_other_date, 'name': name}
filter_args = dict((k,v) for k,v in filter_args.iteritems() if v is not None)
magazines_qs = Magazines.objects.filter(**filter_args)
Note: This of course only works if you donβt have a case where you rely on None
being passed to the filter method.
1
You could do this, assuming parameters are only ever left out and not explicitly passed as None
:
def get_statistics(**kwargs):
return Magazines.objects.filter(**kwargs)
kwargs
will be a dict containing only the keyword arguments that are explicitly passed in. .filter(**kwargs)
unpacks these into keyword arguments that are passed to filter()
.
- Expand search and return all objects Django REST Framework
- Uploading a file using django
- How can I use two functions of the same name in model django
- Exclude date via .exclude
- Django rest frame work : oscarapi authentication is not working
Source:stackexchange.com