【问题标题】:SQL query "translated" to one that Django will accept, anyone? Please (python)SQL 查询“翻译”为 Django 将接受的查询,有人吗?请(蟒蛇)
【发布时间】:2020-09-22 06:47:56
【问题描述】:

任何人都可以将此 MySQL 查询“翻译”为 Django 链或 Q()。这只是一个示例(但有效)查询,但我想亲眼看看,因为 Django 文档在这方面看起来不太友好,我无法让这些链和东西工作。

mysql -> SELECT position, COUNT(position) FROM    
      -> (SELECT * FROM log WHERE (aspect LIKE 'es%' OR brand LIKE '%pj%')
      -> AND tag IN ('in','out')) AS list
      -> GROUP BY position ORDER BY COUNT(position) DESC;

虽然我认为将来链接过滤器对我来说会更方便,但目前下面的内容似乎更简单。

query = "the query from above"

cursor.execute(query)

[new_list.append([item for item in row ]) for row in cursor]

...或者我应该退出()

【问题讨论】:

    标签: python mysql sql django chain


    【解决方案1】:
    from django.db.models import Count,Q
    myfilter = [Q(aspect__startswith="es")|Q(brand__contains="pj"),tag__in=['in','out']]
                #   condition 1           OR     condition2      AND     condition3
    qry = Log.objects.filter(*myfilter).values('position').annotate({"count":Count('position')})
    print(qry.values())
    

    我认为使用 django 可能会得到相同的答案......我认为还是关闭

    我认为它是否更好在旁观者的眼中

    【讨论】:

      【解决方案2】:
      myfilter = Q(aspect__startswith="es") | Q(brand__contains="pj"), Q(tag__in=['in', 'out'])
      qry = Log.objects.filter(*myfilter).values('position').annotate(Count('position')).order_by('-position__count')
      

      必须在 tag__in 之前添加 Q
      myfilter 上的括号没有影响
      annotate({ "count":Count('position')}) 出错QuerySet.annotate() received non-expression(s)
      并按降序排序必须添加 .order_by('-position__count')
      输出是一本字典,但它非常适合在网站上显示

      所以你很亲近。现在数据与 mysql 输出匹配,我更好地理解了如何执行 QuerySets 和过滤器。谢谢

      【讨论】:

        猜你喜欢
        • 2019-09-21
        • 2021-11-26
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 2020-07-05
        相关资源
        最近更新 更多