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?
Django will create or use an autoincrement column named id by default, which is the same as your legacy column.
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.
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.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With