【问题标题】:How to add a "unique_together" constraint to a core model in django?如何在 django 的核心模型中添加“unique_together”约束?
【发布时间】:2019-01-08 10:02:08
【问题描述】:

我正在尝试扩展 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 约束?

【问题讨论】:

标签: django


【解决方案1】:

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

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

这具有能够从任何应用程序更改模型的额外优势。

【讨论】:

    【解决方案2】:

    这可能不是最好的方法,但我可以通过构建自己的迁移文件来添加“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")})
        ]
    

    【讨论】:

    • 这仅在您在 django 应用程序中进行迁移时才有效......在我的情况下,我猜它会尝试更改代理模型,但它没有做任何事情。跨度>
    猜你喜欢
    • 2012-01-05
    • 2019-02-15
    • 2010-11-03
    • 2017-12-08
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    相关资源
    最近更新 更多