doniyor
doniyor

Reputation: 37934

Dynamic object filter

I have a filter query which varies depending on the search criteria,

Sometimes it is:

Thing.object.filter(name__startswith=word).distinct('id')

and sometimes:

Thing.object.filter(city__startswith=word)

So everything after .filter( can change. Is there a way to set this dynamically?

Upvotes: 0

Views: 110

Answers (2)

Dmitry Demidenko
Dmitry Demidenko

Reputation: 3407

If the 'city' and 'name' are values of a criteria selector, you can do something like this:

queryset = Thing.object.filter(**{'%s__startswith' % criteria: word})

if criteria_requires_distinct:
    queryset = queryset.distinct()

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

The arguments to .filter(), yes. Just create a dictionary.

D = {'city__startswith': word}
things = Thing.object.filter(**D)

The call to .distinct(), no. You will need to special case that.

Upvotes: 3

Related Questions