I'm using django + MySQL. Sometimes, I insert duplicate data into my database, which causes django to raise an IntegrityErrror
.
The issue is, django/python use this same error for several of the different MySQL errors. The only way to differentiate between them is to look at the error code. For example,
try:
# code that raises integrity error
except IntegrityError
if e.args[0] == 1062:
raise CustomCreatedDuplicateEntryError
else:
raise e
My question is: Is this safe to do? If so, why isn't this implemented at a lower level? It seems like I can't be the only one who wants more fine grained control over IntegrityError.
Thanks!
EDIT
Code to raise this error
class Foo(django.db.models.Model):
guid = models.CharField(max_length=32, db_index=True, unique=True)
Foo(guid=a).save()
# this raises an IntegrityError with code 1062!
Foo(guid=a).save()
Is this safe to do?
This is not unsafe. Although by doing this you've created a coupling between your application and the database(MySQL). What if down the road you decide to replace MySQL with some other database solution? The error codes will be changed, and your code will raise inconsistent messages.
If so, why isn't this implemented at a lower level?
Probably for the same concern I am having.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With