Django:如何管理特定于数据库的代码?

时间:2022-10-19 23:29:13

I am using the postgres unaccent feature for a django project.

我正在使用postgres unaccent功能进行django项目。

This makes my app database specific and I want to be able to use some others databases (postgres without with extension or others). In this case of course, I don't use unaccent

这使我的应用程序数据库具体化,我希望能够使用其他一些数据库(postgres没有扩展或其他)。在这种情况下,我当然不会使用unaccent

I would like to have something transparent for the user. I image my code should look like something like:

我想为用户提供透明的东西。我想我的代码看起来像:

def get_objects(text):
    try:
        qs = MyModel.objects.extra(
            where=[u"UPPER(unaccent("name")) LIKE UPPER(unaccent(%s))"],
            params = [u"%{0}%".format(text)]
        )
        return list(qs)
    except DatabaseError, msg:
        qs = MyModel.objects.filter(name__icontains=text)
        return list(qs)

Unfortunately, if unaccent is not installed on the database, the DatabaseError is raised but the 2nd query fails with the following error:

不幸的是,如果数据库上没有安装unaccent,则会引发DatabaseError,但第二个查询失败,并显示以下错误:

 DatabaseError: current transaction is aborted, commands ignored until end of transaction block 

I've tried to add transaction support and to rollback it without any success.

我试图添加事务支持并回滚它没有任何成功。

What is the best way to manage this error and make the code working whether unaccent is available or not.

管理此错误的最佳方法是什么,并使代码工作,无论是否有无密码。

1 个解决方案

#1


1  

You can check settings.DATABASE_ENGINE value as follow:

您可以检查settings.DATABASE_ENGINE值如下:

from django.conf import settings

def get_objects(text):
    if settings.DATABASE_ENGINE == 'postgresql_psycopg2':
        qs = MyModel.objects.extra(
            where=[u'UPPER(unaccent("name")) LIKE UPPER(unaccent(%s))'],
            params = [u"%{0}%".format(text)]
        )
        return list(qs)
    else:
        qs = MyModel.objects.filter(name__icontains=text)
        return list(qs)

#1


1  

You can check settings.DATABASE_ENGINE value as follow:

您可以检查settings.DATABASE_ENGINE值如下:

from django.conf import settings

def get_objects(text):
    if settings.DATABASE_ENGINE == 'postgresql_psycopg2':
        qs = MyModel.objects.extra(
            where=[u'UPPER(unaccent("name")) LIKE UPPER(unaccent(%s))'],
            params = [u"%{0}%".format(text)]
        )
        return list(qs)
    else:
        qs = MyModel.objects.filter(name__icontains=text)
        return list(qs)