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.

2
  • 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. Commented Sep 25, 2013 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 Commented Sep 25, 2013 at 14:21

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this suggestion. The problem is that not all postgres db implements the unaccent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.