Is there a way to set the id value of new Django objects to start at a certain value?

前端 未结 2 1085
北恋
北恋 2021-02-19 08:56

Is there a way to set the counter of id values for objects in Django?

For example I have an set of objects \'Video\' that are currently at id=100 the next time I create

相关标签:
2条回答
  • 2021-02-19 09:47

    You can make a fixture that creates a dummy row in your database with ID=1999. The next auto-generated ID would be 2000 then.

    This solution probably depends on you database backend to 'resume where you left off'. At least MySql and PostgreSQL do this (I guess every backend does this).

    There's also a solution for MySql only (as far as I know) that consists of a SQL statement ALTER TABLE tbl AUTO_INCREMENT = 100;

    That wouldn't be database agnostic anymore, though.

    0 讨论(0)
  • 2021-02-19 09:54

    You can specify the ID when you create the object, as long as you do it before you save:

    new = Video()
    new.id = 2000
    new.save()
    

    You could just calculate the ID you wanted each time - though I'm not sure what's wrong with Django's auto ID fields ;)

    0 讨论(0)
提交回复
热议问题