Skip to content

Commit

Permalink
Fix bulk_create without tenant context
Browse files Browse the repository at this point in the history
  • Loading branch information
CleitonDeLima committed Mar 25, 2024
1 parent a72652f commit 8b06055
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
5 changes: 3 additions & 2 deletions easy_tenants/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ def get_queryset(self):
def bulk_create(self, objs, *args, **kwargs):
tenant = get_current_tenant()

for obj in objs:
setattr(obj, field_name, tenant)
if tenant:
for obj in objs:
setattr(obj, field_name, tenant)

return super().bulk_create(objs, *args, **kwargs)

Expand Down
2 changes: 2 additions & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,5 @@

EASY_TENANTS_TENANT_FIELD = "store"
EASY_TENANTS_TENANT_MODEL = "tests.StoreTenant"

USE_TZ = True
17 changes: 17 additions & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,23 @@ def test_bulk_create(tenant_ctx):
assert objs[1].get_tenant_instance() == tenant


@pytest.mark.django_db
def test_bulk_create_without_context():
store1 = StoreTenant.objects.create()
store2 = StoreTenant.objects.create()

objs = [
Product(name="prod1", store=store1),
Product(name="prod2", store=store2),
]
with tenant_context_disabled():
objs = Product.objects.bulk_create(objs)

assert Product.objects.count() == 2
assert objs[0].get_tenant_instance() == store1
assert objs[1].get_tenant_instance() == store2


def test_all_objects(db):
store1 = StoreTenant.objects.create()
store2 = StoreTenant.objects.create()
Expand Down

0 comments on commit 8b06055

Please sign in to comment.