如何在Django的核心模型中添加“ unique_together”约束?

时间:2018-07-31 22:29:28

标签: django

我正在尝试扩展django Group模型,使其对多租户更加友好。基本上,我想删除name字段上的唯一约束,添加一个名为tenant的字段,并使nametenant唯一。到目前为止,我可以完成所有操作,但是无法创建unique_together约束。

这是我到目前为止所拥有的:

from django.contrib.auth.models import Group

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

现在如何创建unique_together约束?

3 个答案:

答案 0 :(得分:1)

这可能不是最好的方法,但是我能够通过构建自己的迁移文件来添加“ unique_together”约束。检查一下:

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")})
    ]

答案 1 :(得分:0)

向内置Django模型添加功能和属性的一种干净方法是通过继承对其进行扩展。您可以尝试以下方法:

class MyGroup(Group):
    name = models.CharField(max_length=200)
    tenant = models.ForeignKey(blah blah blah)

    class Meta:
        unique_together = ('name', 'tenant',)

答案 2 :(得分:0)

不确定这是否正确,但我的解决方案涉及以下方面:

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)
    ]

这具有可以从任何应用程序更改模型的附加优势。