1

I'm fairly new to Django and I'm building a multi tenant app. I'm not really sure how to get the logged in user's current tenant in order to use it as a filter in views. Example: Post.objects.filter(tenant=current_tenant)

Example Models:

from django.db import models

class Tenant(models.Model):
    name = models.CharField(…)

class CustomUser(AbstractUser):
    tenant = models.ForeignKey(Tenant, …)

class Post(models.Model):
    user = models.ForeignKey(CustomUser, …)
    title = models.CharField(…)

class Comment(models.Model):
    post = models.ForeignKey(Post, …)
    text = models.CharField(…)

Where should I write the get_current_tenant function and how should I write it?

Any help would be greatly appreciated.

Hofmann
  • 118
  • 1
  • 8
  • You will have to [extend the user model](https://stackoverflow.com/q/44109/3929826) in some way. Could be a one to one relation to or from the `Tenant`. – Klaus D. Aug 08 '21 at 21:35
  • Thanks for your response, I've updated the question with the user model. Do you have any suggestions on how to write the `get_current_tenant` function and where to place it? – Hofmann Aug 08 '21 at 21:38
  • With that model the user is going to have an attribute `tenant`. No function needed. – Klaus D. Aug 08 '21 at 21:47
  • I understand that I can now access the `tenant` attribute. I would appreciate it if you can explain to me how I can use it in order to make sure that `Class-based views` queries will only return the currently logged in user tenant's related instances. – Hofmann Aug 08 '21 at 22:03
  • Read the link I gave and the links in it! – Klaus D. Aug 08 '21 at 22:21

0 Answers0