An approach to lightweight tenancy management using Django Rest Framework with Eliana Rosselli

Learn how to implement lightweight tenancy management in Django Rest Framework, including filtering queries, restricting access, and using libraries like drf-nested-routers and drf-access-policy to streamline your code.

Key takeaways
  • Multi-tenancy is a software architecture where a single software instance can serve multiple tenants, which are isolated from each other, but share the same application instance and database.
  • In Django, you can achieve multi-tenancy by filtering the queryset using the company ID, and raising a custom exception if the company does not exist.
  • You can use a custom model manager to filter the queryset, and override the all method to include the company filter.
  • You can also use a library like drf-nested-routers to nest your API routes, so that resources are nested under their tenants.
  • It’s important to consistently restrict access to resources, and to avoid code duplication by centralizing all the checks in a single place.
  • You can use an access policy to implement permission checking, and to restrict access to resources based on the tenant.
  • An example of a real-life scenario where multi-tenancy is used is in a cloud-based accounting service, where each client is a separate tenant.
  • To implement multi-tenancy, you need to define what a tenant is, and how to restrict access to resources based on the tenant.
  • You can use an abstract model to replace the default manager, and to implement the company filter.
  • The checks are only done at the viewset level, and you need to implement permission checking at the object level.
  • You can use a library like drf-access-policy to implement permission checking, and to restrict access to resources based on the tenant.
  • It’s important to test your implementation thoroughly, and to ensure that it meets the requirements of your application.
  • An example of a limitation of the approach is that it does not work if you need different schemas for different tenants.
  • You can use a library like Celery to implement background tasks, and to send emails to users.
  • An example of a use case where multi-tenancy is used is in a software as a service (SaaS) application, where each client is a separate tenant.