Django unique=True not working

后端 未结 3 1480
暗喜
暗喜 2020-12-23 18:03

This is from django\'s documentation:

Field.unique

If True, this field must be unique throughout the table.

This is enforced at the databas

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 18:14

    Running sql scripts directly on the db can be avoided. Rather add the sql execution in your migration:

    from __future__ import unicode_literals
    from django.db import migrations, connection
    
    
    def alter_table(apps, schema_editor):
        query ="ALTER TABLE  ADD UNIQUE (unique_col);"
        cursor = connection.cursor()
        cursor.execute(query)
        cursor.close()
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('app', 'yourlastmigration'),
        ]
    
        operations = [        
            migrations.RunPython(alter_table),
        ]
    

提交回复
热议问题