pospolitaki
pospolitaki

Reputation: 353

Is it possible in Django to call custom `QuerySet` method on reverse related objects lookup?

E.g. there are next models and custom QuerySet:

from django.db import models

class ActiveQuerySet(models.QuerySet):
    def active(self):
        '''returns only active objects'''
        '''supposing here would be a lot
           of more complicated code  
           that would be great to reuse
        '''
        return self.filter(is_active=True)   


class Category(models.Model):
    name = models.CharField(max_length=128, blank=True, null=True, default=None)


class Product(models.Model):
    name = models.CharField(max_length=128, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='products', related_query_name="product", blank=True, null=True, default=None)
    objects = ActiveQuerySet.as_manager()

Could you tell me if there is a way to call the active() method like this:

category = Category.objects.first()
category.products.active()

instead of doing like this:

category.products.filter(is_active=True)

Or how to implement appropriately such behavior?

Upvotes: 0

Views: 337

Answers (1)

jTiKey
jTiKey

Reputation: 743

You have to add the custom queryset into the parent model, not the _set. You can change custom_products to any other word.

class ActiveQuerySet(models.QuerySet):
    def active(self):
        '''returns only active objects'''
        '''supposing here would be a lot
           of more complicated code  
           that would be great to reuse
        '''
        return self.products.filter(is_active=True)   

class Category(models.Model):
    name = models.CharField(max_length=128, blank=True, null=True, default=None)
    custom_products = ActiveQuerySet.as_manager()

category.custom_products.active()

Upvotes: 1

Related Questions