title: Why do I need to run the postgresql nextval function? And how to prevent it?
body: <p>I just had an issue with Django and PostgreSQL that I don't understand.</p>
  
  <p>I have a simple model, defined such as:</p>
  
  <pre><code>class MyModel(models.Model):
      my_field = models.IntegerField()
      my_other_field = models.TextField()
  </code></pre>
  
  <p>In my view, i have something similar to:</p>
  
  <pre><code>my_object = MyModel(my_field=1, my_other_field='blah')
  my_object.save()
  </code></pre>
  
  <p>Everything was working fine, until this morning. I got this error:</p>
  
  <pre><code> IntegrityError at /my_url/
  
  duplicate key value violates unique constraint "my_model_pkey"
  DETAIL:  Key (id)=(3) already exists.
  CONTEXT:  Remote SQL command: INSERT INTO public.my_model(id, my_field, my_other_field) VALUES ($1, $2, $3) RETURNING id
  </code></pre>
  
  <p>I had this error once, I know it is related to the way PostgreSQL syncs the sequential table associated with my model with the id column. I has to run this function in PostgreSQL until the <code>id</code> returned was greater than the biggest value of the <code>id</code>.</p>
  
  <pre><code>select nextval('my_model_id_seq'::regclass);
  </code></pre>
  
  <p>My question is: Why did this happen in the first place? And how to prevent it in the future ?</p>
  
  <p>By the way, that's the only way I insert data into the table, I've never inserted data manually.</p>
  
  <p>I hope the question is clear enough</p>