title: How to create Django objects so as to avoid duplicate key errors after restoring your database?
body: <p>In Django, when you create an object, either with a Django helper function like 'create_user' or with an object's 'create' method, Django automatically creates an auto-incrementing primary key for that new object:</p>
  
  <pre><code>user = User.objects.create_user(username='foo', password='bar')
  user.save()   # id = 1
  
  account = Account.objects.create(user=user)
  account.save()   # id = 1
  </code></pre>
  
  <p>But in the real world, if your server crashes and you have to rebuild your database server and then reload all your data, the first time you try to create a new object, you're going to get this type of error:</p>
  
  <pre><code>django.db.utils.IntegrityError: duplicate key value violates unique constraint "new-object_pkey"
  </code></pre>
  
  <p>Whenever you create a new model instance, Django seems to assume you're starting with a clean, new database and it assigns the new object an id of 1 even though, if you had to restore the database,  you already have an object in the restored table with an id of 1.</p>
  
  <p>What is the "Django way" to avoid this situation with both Django's helper functions as well as the object "create" method?  I would think that this would be a common problem for any production Django website and that Django would recognize this and handle it automatically.  But I don't see such a solution discussed anywhere.  How do you avoid this situation?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I've discovered the solution.  Django does not select primary keys, your database does. In the situation I describe, you need to run Django's  'sqlsequencereset' command against your models.  I'll answer my own question in a couple of days to detail how I did this.</p>