0

I need to write the following querysets mixins:

class VendorOwnedQuerySetMixin(models.QuerySet):
    def get_objects_for_vendor(self, request):
        vendor_user = VendorUserModel.objects.get(user=request.user)
        return qs.filter(vendor=vendor_user.vendor)


class OrganizationOwnedQuerySetMixin(object):
    def get_objects_for_organization(self, request):
        return self.filter(organization__domains__name=hostname_from_request(request))

All's working well because some model managers will inherit the first mixin and some inherit the second.

Then inside the get_queryset of the viewset, i will call the appropriate get_objects method.

example

def get_queryset(self, queryset=None):
        return Some.objects.get_objects_for_organization(self.request)

Now I need to have a django rest viewset that needs to run the get_queryset method that runs both filters.

How do I "chain" them within the get_queryset method? Because I want to reuse my code where possible

Kim Stacks
  • 10,202
  • 35
  • 151
  • 282

1 Answers1

1

In order to chain the filters, you need to get the previous queryset. This can be achieved by calling super().get_queryset(request). It will get the queryset from the other classes your view inherit from and will apply the filter:

class VendorOwnedQuerySetMixin(models.QuerySet):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        vendor_user = VendorUserModel.objects.get(user=request.user)
        return qs.filter(vendor__user=vendor_user.vendor)


class OrganizationOwnedQuerySetMixin(object):
    def get_objects_for_organization(self, request):
        qs = super().get_queryset(request)
        return qs.filter(organization__domains__name=hostname_from_request(request)

Remember that you MUST set the mixins before the view in order to work. For example:

class MyView(OrganizationOwnedQuerySetMixin, VendorOwnedQuerySetMixin, RetrieveAPIView):
    ...

A call on get_queryset will get the RetrieveAPIView queryset which will get passed to VendorOwnedQuerySetMixin once the super() call returns, get the filter applied and returns the result to OrganizationOwnedQuerySetMixin after the super() is called which in turn will apply its filter and return the result.

Linovia
  • 19,812
  • 4
  • 47
  • 48