Changing lookup_type in Django 1.10+

122 views Asked by At

In older versions of Django, you could change the lookup on the fly and have access to the value being looked up. For example, let's assume we're storing country by its ISO 2-letter abbreviation, but we want to allow searching by the name of a country.

from .data import COUNTRIES

class CountryField(…):
    def get_prep_lookup(self, lookup_type, value):
        if lookup_type == 'icontains':
            matching_codes = [
                country.code for country in COUNTRIES if value in country.name.lower()
            ]
            lookup_type = "in"
            values = matching_codes
        # ... perform similar for contains, startswith, endswith, etc. lookups
        return super(CountryField, self).get_prep_lookup(lookup_type, value)

As of Django 1.10, get_prep_lookup is deprecated within the Field object. They recommend subclassing Lookup classes and defining get_prep_lookup.

The problem is, as far as I can tell, the implementation for Lookup.get_prep_lookup does not let you change the lookup, and the method also does not receive the lookup value.

0

There are 0 answers