在django中的不同调用期间捕获NotImplemented错误

时间:2016-02-05 02:57:52

标签: python django postgresql sqlite django-queryset

确定。所以SQLLite can't make distinct calls in Django很好。我很好。

所以我正在尝试构建一个可以在任何地方部署的应用程序,主要是Postgres,但偶尔会在其他平台上运行,并希望方法始终返回查询集。

所以我有这样的代码:

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

除了非DISTINCT支持数据库之外,catch 永远不会捕获。我只是得到这个追溯:

>>> 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

如何在这样的链式查询集调用中正确捕获NotImplementedError

1 个答案:

答案 0 :(得分:1)

懒惰地评估查询集。也许异常是在try-except块之外引发的?

您可以在various waystry except内强制进行评估。

try:
    _states = qs.distinct('registrationAuthority')
    bool(_states)  # evaluate queryset
    states = _states
except NotImplementedError:
    # do something to make a clean states variable here

值得注意的是,这不起作用:

try:
    states = qs.distinct('registrationAuthority')
    bool(states)  # evaluate queryset
except NotImplementedError:
    states = states.filter() # error raised here

与异常块一样,states仍然会在末尾链接不同的过滤器,因为当捕获到异常时它不会被剥离