Search code examples
pythondjangodjango-filter

How to change filter queryset depends on user


I am using django-filter and I have two models CustomUser and Shop. How to change filter choices queryset so that user(request.user) can filter only his shops?

User

class CustomUser(AbstractBaseUser, PermissionsMixin):
    shop = models.ManyToManyField(Shop, blank=True, related_name='custom_user')

Shop

class Shop(models.Model):
    address = models.CharField(_('Address'), unique=True, max_length=64, blank=False, null=False, db_index=True)

filters.py

shops = Shop.objects.filter(is_active=True)
SHOP_CHOICES = [('All', 'All')]
for x in shops:
    SHOP_CHOICES.append((x.address, x))
SHOP_CHOICES = tuple(SHOP_CHOICES)


class ShopFilter(django_filters.FilterSet):
    address = django_filters.MultipleChoiceFilter(choices=SHOP_CHOICES)

    class Meta:
        model = Shop
        fields = ['address']

views.py

f = ShopFilter(request.GET)

Solution

  • You can filter the queryset before it's returned using the qs method.

    See Filtering the primary `qs.

    So in your case, you should be able to say:

    @property
    def qs(self):
        parent = super().qs
        owner = getattr(self.request, 'user', None)
    
        return parent.filter(custom_user=owner)
    

    Haven't tested this, but this is definitely the method if you want to make any modifications to the query.