2

I'm trying to extend the django Group model to make it friendlier for multi tenancy. Basically I want to remove the unique constraint on the name field, add a field called tenant, and make name and tenant unique together. So far I can do all of that but I can't create the unique_together constraint.

Here's what I have so far:

from django.contrib.auth.models import Group

Group._meta.get_field('name')._unique = False
Group.add_to_class('tenant', models.ForeignKey(blah blah blah))

Now how would I create the unique_together constraint?

FlashBanistan
  • 426
  • 1
  • 9
  • 25

2 Answers2

2

This may not be the best way to do it, but I was able to add a "unique_together" constraint by building my own migration file. Check it out:

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [("auth", "0012_auto_blah_blah_blah")]

    operations = [
        migrations.AlterUniqueTogether(name="group", unique_together={("name", 
        "tenant")})
    ]
Paul Tuckett
  • 1,023
  • 11
  • 14
  • This only works if you make a migration within the django app... in my case, it would try to change the proxy model i guess, but it didn't do anything to it. – Ren May 22 '20 at 17:16
1

Not sure if it's the right way but my solution involved the following:

def group_constraint(apps, schema_editor):
    Group = apps.get_model("auth", "Group")
    schema_editor.alter_unique_together(Group, {("name",)}, {("name", "tenant")})


class Migration(migrations.Migration):

    dependencies = [
        ('customers', '0089_group'),
    ]

    operations = [
        migrations.RunPython(group_constraint)
    ]

This has the added advantage of being able to change the model from any app.

Ren
  • 4,594
  • 9
  • 33
  • 61
  • Very nice implementation. Yeah, mine requires you to change where your `auth` migrations are being created in the `MIGRATION_MODULES` setting. Also, for anyone reading this, keep in mind you can't do this if you have done this: `Group._meta.get_field('name')._unique = False`. That removes all constraints which will throw an error if you try and add this implementation. – Paul Tuckett May 15 '22 at 16:13