3

Database is MySQL.

I use the django.contrib.auth.

Here is all the info:

manage.py dumpdata auth > my_auth.json --natural --exclude contenttypes

Then I deleted the entire database (drop database my_database), and created a new database (create database new_database)(use ./manage.py syncdb to create all tables).

Then

manage.py loaddata my_auth.json

I Got an error:

IntegrityError: (1062, "Duplicate entry '3-add_author' for key 2")

What's the problem?

Any help will be greatly appreciated. Thank you!

Yuanzhong Deng
  • 218
  • 3
  • 12

1 Answers1

4

(Updated)

You're right (re your comments below). The problem is indeed with auth.permission.

When you run syncdb, auth.permission is populated automatically with default values for all installed models. Any subsequent runs of syncdb will add new entries for any models that were recently added.

If at a later stage you reset the database and run syncdb again, the values will be repopulated and depending on the order in which installed models are inspected, the associated permissions may be added in a different order giving it different ids from your previous database (if models were installed in stages).

To avoid this problem, you can either leave auth.permission out when dumping your auth data (as you've already pointed out in your comments), or resetting the auth.permission table before loading your data dump.

Also, it is important to use natural keys (--natural) when dumping out your data so that it does not reference related data using its integer id (which may not be the same when loaded in another db). This feature was introduced in Django 1.2.

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
  • Entries are not exist in the database. I drop the old database, and create a new one (an empty database). I can dump and load successfully for my another app in the same way. – Yuanzhong Deng Sep 12 '11 at 10:21
  • @Yuanzhong You should update your question with that information. All you've mentioned in the question is `dumpdata` followed by `loaddata` which will definitely lead to an `IntegrityError`. – Shawn Chin Sep 12 '11 at 10:25
  • By the way, which tables did you drop and how did you create your new one? Using `./manage.py syncdb`? – Shawn Chin Sep 12 '11 at 10:26
  • Excuse me, I've added more information. I dropped entire database and created a new database. use ./manage.py syncdb to create all tables. Then loaddata. – Yuanzhong Deng Sep 12 '11 at 11:52
  • I know the cause of my problem. The "pk" of auth.permission(add_author) is different between old_database and new_database(use manage.py syncdb to create auth.permission table).(See http://i.stack.imgur.com/PtxDu.jpg for detail) But I have no idea why they are different. Now I add an option "**--exclude auth.permission**" to dumpdata: > manage.py dumpdata auth > my_auth.json --natural --exclude contenttypes **--exclude auth.permission** It work when I load it. Thanks for your answers. – Yuanzhong Deng Sep 12 '11 at 12:52