bernardopires / django-tenant-schemas

Tenant support for Django using PostgreSQL schemas.
https://django-tenant-schemas.readthedocs.org/en/latest/
MIT License
1.45k stars 425 forks source link

weird behaviour using "with schema_context" #667

Closed cyberpunx closed 3 years ago

cyberpunx commented 3 years ago

Hi! Maybe someone can help me figuring out what is happening here.

I have the User model inside both my public schema and my tenant schemas

When I do this

with schema_context("my_schema"):
    users_in_tenant = User.objects.all()

print(users_in_tenant)

it prints all my public users. Not my my_schema users. But when I do this:

user_list = []
with schema_context("my_schema"):
    users_in_tenant = Usuario.objects.all()
        for u in users_in_tenant:
            user_list.append(u)

print(user_list)

it prints correctly the users inside my_schema

Is this working as intended? any thoughts? Thank you in advance!

crstnrm commented 3 years ago

Hi! My english is intermediate, so i will try to be clear :) Querysets is lazy loading, so it doesn't hit your database until you need it. In the first code fragment the query actually hit the database out your with because you don't use the results in the with block. In the second code fragment in the for clause your hit the database so the result is as you expected. In django if you use values function it hit immediately the database, it could be something like that: Usuario.objects.all().values(). I hope be clear.

cyberpunx commented 3 years ago

Yes! You were very clear, thank you for your explanation. So it's a queryset thing, not a schema_context problem. I'm 100% going to use the Usuario.objects.all().values() trick !

Sorry for the inconvenience opening a issue because of this. I'm relatevely new to django and totaly noob with django-tenant-schemas.

crstnrm commented 3 years ago

Yes, there is no problem, everybody is noob at the beginning. Yes it's a django thing, also I have to say values function return the results as list of dict, another options is: users_list = list(Usuario.objects.all()). Anyway, you can get more info here: https://docs.djangoproject.com/en/3.1/topics/db/optimization/#understand-querysets