Auto Incremement when id=0 in dict is passed to save()

from .models import DummyModel
dict = {'id': 0, 'fieldA': 'value-1', 'fieldB': 'value-2', 'fieldC': 'value-3', 'active_flag': 0, 'date': '2024-03-11'}
dummy = DummyModel(**dict)
dummy.save()

ValueError: The database backend does not accept 0 as a value for AutoField.

I thought that if id is 0 it’ll automatically do a auto increment ?

Hey there!
If you primary key field is auto-generated (in this case the id field) then you should not initialize the model with a value if you want it to be auto-generated.
This happens because django uses the same method to create/update (save method), so after a auto-generated field has a value populated, it won’t generate a new one. Otherwise instead of updating a row, it would be creating a new one every-time.

If you have control over the dict creation/initialization you can omit the id field of the keys.
If you don’t have control over the dict creation/initialization you can remove that key if the value is 0.

So I’ve edited my code to as follows :

_id = int(d.get("id", "0"))
dict['id'] = _id
fields = list(dict.keys())

if _id > 0:
    fields.remove('id')
    dummy = DummyModel(**dict)
    dummy.save(force_update=True, update_fields=list(fields))
else:
    del dict['id']
    dummy = DummyModel(**dict)
    dummy.save()

_id = dummy.id

Is there any particular reason for you not to query the DummyModel object from the database? This seems a bit “exotic” way of updating the object, skipping validation and shooting yourself on the foot.

Im using the same code for insert and update. The form UI is the same for both.