Django south migration error with unique field in postgresql database

Edit: I understand the reason why this happened. It was because of the existance of initial_data.json file. Appereantly, south wants to add those fixtures after migration but failing because of unique property of a field.

Hi,

I changed my model from this:


    class Setting(models.Model):
        anahtar = models.CharField(max_length=20,unique=True)
        deger = models.CharField(max_length=40)

        def __unicode__(self):
            return self.anahtar

To this,


    class Setting(models.Model):
        anahtar = models.CharField(max_length=20,unique=True)
        deger = models.CharField(max_length=100)

        def __unicode__(self):
            return self.anahtar

Schema migration command completed successfully, but, trying to migrate gives me this error:

IntegrityError: duplicate key value violates unique constraint "blog_setting_anahtar_key"

DETAIL: Key (anahtar)=(blog_baslik) already exists.

I want to keep that field unique, but still migrate the field. By the way, data loss on that table is acceptable, so long as other tables in db stay intact.


It's actually the default behavior of syncdb to run initial_data.json each time. From the Django docs:

If you create a fixture named initial_data.[xml/yaml/json], that fixture will be loaded every time you run syncdb. This is extremely convenient, but be careful: remember that the data will be refreshed every time you run syncdb. So don't use initial_data for data you'll want to edit.

See: https://docs.djangoproject.com/en/dev/howto/initial-data/#automatically-loading-initial-data-fixtures

Personally, I think the use-case for initial data that needs to be reloaded each and every time a change occurs is retarded, so I never use initial_data.json.

The better method, since you're using South, is to manually call loaddata on a specific fixture necessary for your migration. In the case of initial data, that would go in your 0001_initial.py migration.

def forwards(self, orm):
    from django.core.management import call_command
    call_command("loaddata", "my_fixture.json")

See: http://south.aeracode.org/docs/fixtures.html

Also remember that the path to your fixture is relative to the project root. So, if your fixture is at "myproject/myapp/fixtures/my_fixture.json" call_command would actually look like:

call_command('loaddata', 'myapp/fixtures/my_fixture.json')

And, of course, your fixture can't be named 'initial_data.json', otherwise the default behavior will takeover.

链接地址: http://www.djcxy.com/p/38678.html

上一篇: 产品目录:按参数过滤

下一篇: Django南迁移错误与postgresql数据库中的唯一字段