[Fixed]-How to manage.py loaddata in Django

43👍

Try it like this:

python manage.py dumpdata --natural-foreign \
   --exclude=auth.permission --exclude=contenttypes \
   --indent=4 > data.json
👤ugosan

1👍

Watch out for @receiver in your models. They might be your issue, as they were mine.

I just want to point out my case here. I had a receiver in my model.
Basically, to create a few instances for extra data to my user, like so.

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(account=instance)
        Preferences.objects.create(account=instance)

Running loaddata breaks into "duplicate key value" because my fixture have these rows and my receiver tries to do it as well. Commenting those lines out, running the command and uncommenting did the trick for me.

Maybe there is some sort of flag for "disable receivers" that I do not know about. This seems like something too expected to not be solved by the Django crew.

0👍

I also got this error with loaddata:

Could not load contenttypes.ContentType(pk=2): duplicate key value
violates unique constraint
"django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key
(app_label, model)=(project, address) already exists.

The problem was that the dump did not have all the database migrations that I had in the target system. So make sure you have the migration level that equals to the dump.

👤iqqmuT

Leave a comment