jeudi 4 février 2016

Catching a NotImplemented error during a distinct call in django

Ok. So SQLLite can't make distinct calls in Django. Fine. I'm ok with that.

So I'm trying to build an app that can be deployed anywhere, mostly Postgres, but occasionally on other platforms and want a method to always return a queryset.

So I have code like this:

try:
    states = qs.distinct('registrationAuthority')
except: # (NotImplementedError, e):
    print(e)
    print(e.message)
    if e.message == "DISTINCT ON fields is not supported by this database backend":
        current = []
        seen_ras = []
        for s in states:
            ra = s.registrationAuthority
            if ra not in seen_ras:
                current.append(s.pk)
                seen_ras.append(ra)
        # We hit again so we can return this as a queryset
        states = states.filter(pk__in=current_ids)
    else:
        raise
return states

Except on a non-DISTINCT supporting database, the catch never catches. I just get this traceback:

>>> p.current_statuses()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 138, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 162, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 238, in iterator
    results = compiler.execute_sql()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 829, in execute_sql
    sql, params = self.as_sql()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 393, in as_sql
    result.append(self.connection.ops.distinct_sql(distinct_fields))
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/operations.py", line 132, in distinct_sql
    raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')
NotImplementedError: DISTINCT ON fields is not supported by this database backend

How can I properly catch a NotImplementedError in a chained queryset call like this?

Aucun commentaire:

Enregistrer un commentaire