Django-区分不同类型的IntegrityError [英] Django - Distinguish different types of IntegrityError

查看:251
本文介绍了Django-区分不同类型的IntegrityError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django + MySQL.有时,我将重复的数据插入数据库中,这导致django引发IntegrityErrror.

I'm using django + MySQL. Sometimes, I insert duplicate data into my database, which causes django to raise an IntegrityErrror.

问题是,django/python对多个不同的 MySQL错误.区分它们的唯一方法是查看错误代码.例如,

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

我的问题是:这样做安全吗?如果是这样,为什么没有在较低的级别上实现呢?似乎我不是唯一一个想要对IntegrityError进行更细粒度控制的人.

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.

谢谢!

编辑

引发此错误的代码

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?

这不是不安全的.尽管这样做可以创建应用程序和数据库(MySQL)之间的耦合.如果将来您决定用其他一些数据库解决方案代替MySQL怎么办?错误代码将被更改,并且您的代码将引发不一致的消息.

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.

这篇关于Django-区分不同类型的IntegrityError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆