citusdata / django-multitenant

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

Duplicate key value integrity error thrown if updating tenant model instance with different tenant set #86

Closed rob101 closed 3 years ago

rob101 commented 4 years ago

When updating a tenant model if another current tenant is set then an integrity error is thrown due to a duplicate key value.

For example, consider the following tenant model:

from django_multitenant.mixins import TenantModelMixin

  class Store(TenantModelMixin):
    tenant_id = 'id'
    name =  models.CharField(max_length=50)

Create 2 objects and set the current tenant to the first:

s1 = Store.objects.create(name="store1")
s2 = Store.objects.create(name="store2")
set_current_tenant(s1)

Then attempt to update the second object s2 whilst the current_tenant is still set to s1.

s2.name = 'new name'
s2.save()

This results in:

IntegrityError at /store/settings/1/
duplicate key value violates unique constraint "store_pkey"
DETAIL:  Key (id)=(1) already exists.
rob101 commented 3 years ago

Just to add further clarity; this edge case occurs only when you don't use the TenantManagerMixin on the tenant model.

This actually makes sense, as in the example above I might want a simple administrative ListView for all my stores (tenants), which I otherwise would not be able to see if I was filtering the queryset.

louiseGrandjonc commented 3 years ago

Hi Rob, I noticed that I didn't tell you about the PR I created to fix that issue. Sorry about that. Here it is. https://github.com/citusdata/django-multitenant/pull/88 I'll merge and release a new version sometimes next week. If you have time to test it to double check that it fixes your issue, it would be great.

rob101 commented 3 years ago

@louiseGrandjonc Yes, I have tested this and #88 resolves this issue. Thanks

louiseGrandjonc commented 3 years ago

Great, thank you! I've released a new version 2.2.4 with the fix