[Django]-Django Model not automatically creating ID

8👍

You need to understand what does auto incrementing mean. It means it’s an integer that increases by itself so you don’t need to bother assigning a new integer to it every time you create a database record. If you insert the first record, database would automatically give it id as 1. Next time you inserts a records, database gives it id 2 and so on.

You were trying to give username123 to the id field, which there’s no way for django(and for anybody) to know what’s the next available id for username123.

So the best action is: never explicitly give an id to a model object, because your database will generate one for you. I hope that makes sense.

Edit:

You should NEVER create an object this way:

d = Device("username123", "device12", "manufact12")

It’s a common bad practice for sql statement and django as well: not specify which field to take which value. If your model changed later, you would assign the value to the wrong field. Always do this:

d = Device(field1="username123",
           field2="device12",
           field3="manufact12")

Also for completeness, the error you had was telling you: since you didn’t specify which value assign to which field, I would assign them in sequence, so the first value should assign to id. However, since id field is an integer field(auto increment), I would try to use int() to convert it to integer and store the value. But apparently int("username123") is invalid statement, hence the error.

Leave a comment