8

i have a model with just one field. name.

class City(models.Model): <br>
    name = models.CharField(max_length=30)

Django sets id by itself so I end up with id and a description field in SQL.

but that id field is always increment by 1. I want to start it from 1000 and then increment by one.

Is there any way to do this in Django?

6
  • No, you have to do this at the MySQL level using ALTER TABLE tbl AUTO_INCREMENT = 1000;. Django isn't and should not be responsible for this. Commented May 21, 2013 at 6:38
  • 2
    i just wanted to ask, iff there is some way to set by django? because, the on other system, sync db would not help. and you have to run that script again, ALTER TABLE tbl AUTO_INCREMENT = 1000; Commented May 21, 2013 at 6:39
  • For 15 chars: No. The AutoField is just a representation for the underlying database structure. Django has no control of that. Commented May 21, 2013 at 6:42
  • "I want to start it from 1000" - why?? If it's a synthetic key, its value shouldn't matter... Commented May 21, 2013 at 7:16
  • @eggyal i have a table(change_table) it has that ID, that starts from 0, and i have to have another unique identifer for the each change, that should start from 1000. so each entry in the table then have two ids, one starting from 1,2 and the other visible ID, that has to start from 1001? how i should deal it? Commented May 25, 2013 at 7:06

2 Answers 2

3

I know this question is old, but I'm posting this method for those who find this question in search results and need a good solution for more recent Django versions (i.e. Django >= 1.8):

Create a data migration as documented here. This solution will run when you migrate your app (and, probably, as part of your deployment strategy) and allows you to write code that caters to the specific needs of your database.

I consider this the cleanest method of setting an initial value for auto-incrementing database fields in Django >= 1.7 because it takes advantage of standard Django migrations and doesn't hijack other features of the framework in ways that may not work in the future.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use initial data to give your models ids from 1000. I think if the first models PK is 1000 django will continue with 1001.

Or you create a attribute called custom_id which is always 1000+id. This way you have an additional field in your DB but it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.