'PeeWee Integer Primary Key needs force_insert=True
I am using the excellent PeeWee module to save some Ids and hostnames to a MySQL table.
I want the 'clientId' (which is an IntegerField) to be the primary key, but I seem to need to use save(force_insert=True) to make it insert - otherwise I get nothing added to the table. I don't get any error messages.
I thought this was only supposed to be needed if the primary_key field was NOT an Integer.
I am referring to the documentation - (https://peewee.readthedocs.org/en/2.0.2/peewee/fields.html#non-integer-primary-keys)
My Model:-
class BaseModel(peewee.Model):
class Meta:
database = db
class Client(BaseModel):
clientId = peewee.IntegerField(primary_key=True)
clientName = peewee.TextField()
isDeletedClient = peewee.BooleanField(default=False)
#Create object to insert using collected data...
clientEntry = Client(clientId=clientId,
clientName=clientName,
isDeletedClient=isDeletedClient)
#clientEntry.save() # <-- Nothing gets inserted
clientEntry.save(force_insert=True) # <-- Works.
Thankyou so much for responding. I believe that I was using the save() method incorrectly. Rather than save(), which can do an update if the record already exists with a primary key, I should have been using create(), because my script is always creating a new, empty table then populating it.
So now my model remains the same, but inserting a row becomes...
clientEntry = Client.create(clientId=clientId,
clientName=clientName,
isDeletedClient=isDeletedClient)
Solution 1:[1]
This is a subtle point, but if you want auto incrementing primary key fields, you should use PrimaryKeyField rather than IntegerField(primary_key=True).
This should fix the issue:
class Client(BaseModel):
clientId = peewee.PrimaryKeyField()
clientName = peewee.TextField()
isDeletedClient = peewee.BooleanField(default=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | coleifer |
