python - In Django, how does one filter a QuerySet with dynamic field lookups? -


given class:

from django.db import models  class person(models.model):     name = models.charfield(max_length=20) 

is possible, , if how, have queryset filters based on dynamic arguments? example:

 # instead of:  person.objects.filter(name__startswith='b')  # ... and:  person.objects.filter(name__endswith='b')   # ... there way, given:  filter_by = '{0}__{1}'.format('name', 'startswith')  filter_value = 'b'   # ... can run equivalent of this?  person.objects.filter(filter_by=filter_value)  # ... throw exception, since `filter_by` not  # attribute of `person`. 

help appreciated & thank in advance.

python's argument expansion may used solve problem:

kwargs = {     '{0}__{1}'.format('name', 'startswith'): 'a',     '{0}__{1}'.format('name', 'endswith'): 'z' }  person.objects.filter(**kwargs) 

this common , useful python idiom.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -