Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Python loaddata fails with django.db.utils.IntegrityError

Tags:

python

django

Took over a database project and I am struggling to load the remote database into the local database.

The app was built with django and the local database still relies on sqlite that comes with out of the box.

The remote database is of postgresql type.

The code I am trying to run in the terminal:

python manage.py loaddata *[path to backup.json file]*

I get some integrity error so like any reasonable man I flushed the local db because since I want to anyhows load the remote data.

python manage.py flush python manage.py syncdata

Now when I try to load the data from the json file I get the following error:

django.db.utils.IntegrityError: Problem installing fixture 'C:...\lit\backups\dbbackup_20190915_145546.json': Could not load contenttypes.ContentType(pk=1): UNIQUE constraint failed: django_content_type.app_label, django_conten t_type.model

Changing the settings.py file from:

`DATABASES = {
    'default':  {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}`

to

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'lit',
        'USER': 'admin',
        'PASSWORD': 'admin',
        'HOST': 'localhost',
        'PORT': '5432'
    }

just gives me a new error.

django.db.utils.IntegrityError: Problem installing fixture 'C:..\lit\backups\dbbackup_20190915_145546.json': Could not load contenttypes.ContentType(pk=17): duplicate key value violates unique constraint "django_content_type_a pp_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(admin, logentry) already exists.

I already ran

python manage.py makemigrations
python manage.py migrate
like image 658
RMS Avatar asked Sep 16 '19 14:09

RMS


1 Answers

in your local database you create some ContentType instances.

when you migrate your remote database all ContentType for your models created again.

but when you want to load data you try to load this instances again.

you have 2 solutions

1- remove all content types instances from remote host using django shell

python manage.py shell

>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.all().delete()

2- remove content type instances from dumped data

python manage.py dumpdata --exclude contenttypes
like image 170
vorujack Avatar answered Oct 29 '22 19:10

vorujack