I am attempting to save a simple device model, which has three fields, username, device_name and manufacturer.
Looking at the model in the Database, an ID field was added as the Primary Key. This field should auto increment.
After reading some documentation, I have tried to recreate the following even:
Auto-incrementing primary keys¶
If a model has an AutoField — an auto-incrementing primary key — then that
auto-incremented value will be calculated and saved as an attribute on your
object the first time you call save():
>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id # Returns None, because b doesn't have an ID yet.
>>> b2.save()
>>> b2.id # Returns the ID of your new object.
When doing that for my device model:
>>> d = Device("username123", "device12", "manufact12")
>>> d.id
>>> 'username123'
If I attempt to save this model it will give me the following error:
ValueError: invalid literal for int() with base 10: 'username123'
So it is trying to save 'username123' as the ID. If I create the following device:
>>> d = Device("1", "username123", "device12", "manufact12")
It creates the device with no problem.
Can anyone explain why this is happening?
Edit: After seeing the first reply, it seems that my post was not clear. Here is my model from Django:
class Device(models.Model):
username = models.CharField(max_length=100)
device_name = models.CharField(max_length=100)
manufacturer = models.CharField(max_length=100)
It does not have an ID. As I said in my post, when I try to create the model without the ID (as I would expect to do) it gives me an error. If I explicitly state an ID it works, but as you said, that is not how this is supposed to work.