Creating custom Field Lookups in Django

前端 未结 4 884
悲&欢浪女
悲&欢浪女 2020-12-30 07:48

How do you create custom field lookups in Django?

When filtering querysets, django provides a set of lookups that you can use: __contains, __iexa

4条回答
  •  孤独总比滥情好
    2020-12-30 08:48

    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)
    

提交回复
热议问题