Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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 an object of type 'Video' it will be id=101. However I'd like to have all newly created Video objects start at id=2000. is there a way to do this?

like image 941
9-bits Avatar asked Dec 08 '11 14:12

9-bits


People also ask

Does Django create ID automatically?

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

Does Django create ID field?

An id field is added automatically, but this behavior can be overridden. See Automatic primary key fields. The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it's worth noting Django uses SQL tailored to the database backend specified in your settings file.

What is first () in Django?

first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None.

What is __ str __ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


1 Answers

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 ;)

like image 51
Ben Avatar answered Oct 22 '22 14:10

Ben