Easier chainability with custom QuerySets

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.db import models
from django.db.models.query import QuerySet

class PersonQuerySet(QuerySet):
    def men(self):
        return self.filter(sex='m')
    def women(self):
        return self.filter(sex='f')

class PersonManager(models.Manager):
    def get_query_set(self):
        PersonQuerySet(self.model, using=self._db)
    def men(self):
        return self.get_query_set().men()
    def women(self):
        return self.get_query_set().women()
    
class Person(models.Model)
    name = models.CharField()
    birth_date = models.DateField()
    sex = models.CharField(max_length=1)

    objects = PersonManager()

qs = Person.objects.filter(birth_date__year=1978)
qs.men().filter(name__icontains='Bob')

More like this

  1. Custom managers with chainable filters by itavor 5 years, 4 months ago
  2. TaggedManager and TaggedQuerySet with chainable tagged() methods implemented with django-tagging by fish2000 3 years, 2 months ago
  3. Tatsypie: additional list endpoints for custom Model's manager methods by migajek 6 months ago
  4. Chainable custom query manager for randomize. by I159 1 year, 8 months ago
  5. CustomQueryManager by zvoase 4 years, 10 months ago

Comments

(Forgotten your password?)