【问题标题】:How to Convert Q Object of Django Queryset into SQL?如何将 Django Queryset 的 Q 对象转换为 SQL?
【发布时间】:2021-11-22 06:07:32
【问题描述】:

假设我们有一个像这样的 Q 表达式:

Q(price__lt=160) | Q(publishing_date__year__gte=2016)

此表达式的 SQL 表达式为:

price < 160 OR YEAR(publishing_date) >= 2016

我想要一个将 Django 的 Q 对象转换为 SQL 等价物的包。喜欢:

q_obj = Q(price__lt=160) | Q(publishing_date__year__gte=2016)
sql_expression = q_obj_to_sql(q_obj) # Please, recommend if there exists such a thing

注意: 虽然 Django 提供了将 Querysets 转换为 SQL 的方法,但是,我需要转换 Q 对象,而不是 Querysets。

【问题讨论】:

    标签: python mysql django django-queryset


    【解决方案1】:

    你可以这样做:

    # is a model expample
    class MyModel(models.Model):
        price = models.IntegerField()
        publishing_date = models.DateField()
        ...
    
    
    from django.db.models.sql.query import Query
    from django.db.models import Q
    from django.db.models.sql.compiler import SQLCompiler
    from django.db import connection
    
    # your Q filter
    _filter = Q(price__lt=160) | Q(publishing_date__year__gte=2016)
    _query = Query(MyModel) # replace "MyModel" with your model
    
    _compiler = SQLCompiler(_query, connection, None)
    query_str, args = _filter.resolve_expression(_query).as_sql(_compiler, connection)
    # query_str is a string, the result is 
    #        '("my_model"."price" < %s OR "my_model"."publishing_date" >= %s)'
    # args is a list, result is
    #         [160, '2016-01-01']
    
    # for replace arguments in query_str
    result = query_str % tuple(args)
    # WARNING , don't do this !! Security issue with sql injections.
    # result :
    #     '("my_model"."price" < 160 OR "my_model"."publishing_date" >= 2016-01-01)'
    

    【讨论】:

    • 在这种情况下,我需要一个模型,并且Q 查询中提到的字段必须存在于模型中。但是,我的情况是我没有任何模型。我只有一些 Django 查找,我需要将它们转换为 SQL。它应该独立于模型的定义。
    • django 需要模型来构造查询集和 Q 过滤器以使用模型字段检查/替换字段,如果您没有任何模型,则不能使用 django 进行此操作
    猜你喜欢
    • 2011-03-14
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2012-03-31
    • 2013-08-11
    • 2013-09-07
    相关资源
    最近更新 更多