How do you create custom field lookups in Django?
When filtering querysets, django provides a set of lookups that you can use: __contains, __iexa
A more flexible way to do this is to write a custom QuerySet as well as a custom manager. Working from ozan's code:
class PersonQuerySet(models.query.QuerySet):
def in_age_range(self, min, max):
return self.filter(age__gte=min, age__lt=max)
class PersonManager(models.Manager):
def get_query_set(self):
return PersonQuerySet(self.model)
def __getattr__(self, name):
return getattr(self.get_query_set(), name)
class Person(models.Model):
age = #...
objects = PersonManager()
This allows you to chain your custom query. So both these queries would be valid:
Person.objects.in_age_range(20,30)
Person.objects.exclude(somefield = some_value).in_age_range(20, 30)