django-extra-settings
django-extra-settings copied to clipboard
Updating setting give unique constraint error
Python version 3.12
Django version 5.0.7
Package version 0.12.0
Current behavior (bug description)
Django Version: | 5.0.7 IntegrityError UNIQUE constraint failed: extra_settings_setting.name
When using the update code from the docks I get a a unique constraint error. Here is some sample code that does not work:
counter = Setting.get("COUNTER", 0) setting_object = Setting(name="COUNTER", value=counter, value_type="int") setting_object.value += 1 setting_object.save()
The first run works, any run after that gives unique constraint error.
Expected behavior
I would expect the value of COUNTER to be incremented.
Upvote & Fund
- We're using Polar.sh so you can upvote and help fund this issue.
- We receive the funding once the issue is completed & confirmed by you.
- Thank you in advance for helping prioritize & fund our backlog.
@cabsil22 thank you for reporting this, could you provide a failing unittest please?
@cabsil22 your code is wrong, that's the cause of the IntegrityError.
# this get a setting value, if it doesn't exist, the default value is returned
counter = Setting.get("COUNTER", 0)
# this creates a setting object, so the first time it works, the second time it raises the exception because a setting with name COUNTER already exists.
setting_object = Setting(name="COUNTER", value=counter, value_type="int")
setting_object.value += 1
setting_object.save()
Setting is a model, for your use case you should use the get_or_create method:
https://docs.djangoproject.com/en/5.1/ref/models/querysets/#get-or-create
Please forgive me if I am missing something, but your recommended code is exactly what my pull request has as a suggested fix for the read me. The readme does not explain correctly how to update a setting. That is the issue here. On Sep 21, 2024 6:51 AM, Fabio Caccamo @.***> wrote: @cabsil22 your code is wrong, that's the cause of the IntegrityError.
this get a setting value, if it doesn't exist, the default value is returned
counter = Setting.get("COUNTER", 0)
this creates a setting object, so the first time it works, the second time it raises the exception because a setting with name COUNTER already exists.
setting_object = Setting(name="COUNTER", value=counter, value_type="int") setting_object.value += 1 setting_object.save() Setting is a model, for your use case you should use the get_or_create method: https://docs.djangoproject.com/en/5.1/ref/models/querysets/#get-or-create
—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: @.***>
@cabsil22 just do:
counter, _ = Setting.objects.get_or_create("COUNTER", defaults={
"value_type": Setting.TYPE_INT,
"value": 0,
})
counter.value += 1
counter.save()