1

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

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

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:

 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.

luc
  • 41,928
  • 25
  • 127
  • 172
  • you have a syntax error. The `)` in the `try` block should be before `return list(qs)`. Now, `return qs` is being sent into the `extra()` as a part of the SQL statement, and it is failing. – karthikr Sep 25 '13 at 14:18
  • thanks, i think it's fixed. This is not the real code... just something to try to explain what i want to do – luc Sep 25 '13 at 14:21

1 Answers1

1

You can check settings.DATABASE_ENGINE value as follow:

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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Thanks for this suggestion. The problem is that not all postgres db implements the `unaccent` – luc Sep 26 '13 at 05:51