Django 自定义查找 运行 不同于 str(query) 中显示的 SQL 查询

Django Custom lookup running different SQL query than it's displaying in str(query)

考虑以下 urls.py - 为简洁起见,我决定将示例放在一个文件中:

from django.conf.urls import patterns, include, url

from django.http import HttpResponse
from django.db import models

def x(request):
    class A(models.Model):
        title = models.CharField(max_length=1024)
    class RightAnchored(models.Lookup):
        lookup_name = 'rightanchored'

        def as_sql(self, compiler, connection):
            lhs, lhs_params = self.process_lhs(compiler, connection)
            rhs, rhs_params = self.process_rhs(compiler, connection)
            params = lhs_params + rhs_params
            return "REVERSE(%s) LIKE REVERSE(%s)" % (lhs, rhs), params

    models.CharField.register_lookup(RightAnchored)
    q = A.objects.filter(title__rightanchored='%b')
    return HttpResponse(str(q.query))

urlpatterns = patterns('',
    url(r'^$', x),
)

出于某种原因,访问 http://localhost:8000 会得到:SELECT "w_a"."id", "w_a"."title" FROM "w_a" WHERE REVERSE("w_a"."title") LIKE REVERSE(%b),而 运行 命令会导致 SELECT "w_a"."id", "w_a"."title" FROM "w_a" WHERE REVERSE("w_a"."title") LIKE REVERSE('%b')(注意额外的 '' LIKE REVERSE 内)。这意味着显示的查询与 运行 中的查询不同。当 str(q.query) 被调用时,如何使我的 Lookup 正常运行?

str(qs.query) 并未在所有后端进行正确引用。这是因为引用由数据库驱动程序处理,而某些驱动程序不允许访问引用的查询字符串。

所以,简而言之,一切正常。