[Fixed]-Django. ORM filter by function's keyword argument

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().

Leave a comment