[Fixed]-Django queryset subset with custom manager?

1👍

You can do it in many ways. Some of them:

  • Make all calculation in the view and pass to the context prepared data:

    customers = Customer.objects.filter(name="foo")
    active_customers_count = customers.filter(is_active=True)
    
  • Custom template tag (docs):

    tag

    from django import template
    
    register = template.Library()
    
    
    @register.assignment_tag
    def filter_qs(qs, **kwargs):
        return qs.filter(**kwargs)
    

    template

    {% filter_qs customers is_active=True as active_customers %}
    {{ active_customers|length }}            
    
  • Custom Manager with custom QuerySet (docs):

    models

    class IsActiveQuerySet(models.QuerySet):
        def active(self):
            return self.filter(is_active=True)
    
    
    class IsActiveManager(models.Manager):
        def get_queryset(self):
            return IsActiveQuerySet(self.model, using=self._db)
    
    
    class Customer(BaseInfo):
       objects = IsActiveManager()
       name = models.CharField(max_length=50)
    

    template

    {{ customers.active|length }}
    

I would strongly recommend you to go with the first option, it will be the most “Pythonic” way.
Anyway django will make 2 separate sql queries for any of solution listed above.

Leave a comment