citusdata / django-multitenant

Python/Django support for distributed multi-tenant databases like Postgres+Citus
MIT License
721 stars 119 forks source link

Issue with using TenantModel in DjangoRestFramework viewsets #7

Open gsgalloway opened 6 years ago

gsgalloway commented 6 years ago

To use TenantModel with Django Rest Framework's ViewSets, the following refactor was necessary:

# before
class MyModelViewSet(GenericViewSet):
  queryset = MyModel.objects.all()
# after
class MyModelViewSet(GenericViewSet):
    def get_queryset(self):
        return MyModel.objects.all()
saicitus commented 6 years ago

Another approach is to create a subclass with the suitable get_queryset and make all your viewsets inherit this subclass. For ex:

class TenantModelViewSet(GenericViewSet):
  def get_queryset(self):
        return TenantModel.objects.all()
class MyModelViewSet1(TenantModelViewSet):
  ...
class MyModelViewSet2(TenantModelViewSet):
  ..
ebspeter commented 4 years ago

Another gotcha is that you'll need to register the route with the extra basename kwarg when using get_queryset():

router = routers.DefaultRouter()
router.register(r'mymodel', MyModelViewSet, basename="mymodel")