在djang中的非重复调用期间捕获NotImplemented错误

2024-09-30 12:15:11 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧。所以SQLLite can't make distinct calls in Django很好。我同意。在

因此,我试图构建一个可以部署在任何地方的应用程序,主要是Postgres,但偶尔也会在其他平台上,并希望有一个方法总是返回一个queryset。在

所以我有这样的代码:

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从不捕获。我刚得到回溯:

^{pr2}$

如何在这样的链式queryset调用中正确地捕捉NotImplementedError?在


Tags: inmessageifcurrentcanquerysetraprint
1条回答
网友
1楼 · 发布于 2024-09-30 12:15:11

查询集被延迟地计算。可能异常是在try-except块之外引发的?在

您可以在various ways中的try except中强制求值。在

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

请注意,这是行不通的:

^{pr2}$

与在异常块中一样,states的末尾仍将链接不同的筛选器,因为在捕获异常时,^{没有剥离。在

相关问题 更多 >

    热门问题