【问题标题】:Is there any way to convert this into django orm?有没有办法把它转换成 django orm?
【发布时间】:2019-09-15 14:33:57
【问题描述】:

我需要获取table1 中的所有行,即使它在table2 中不存在,并将其显示为零。我使用raw sql query 得到它,但在 django ORM 中,我得到的值仅存在于table2 中。 我的 django orm 的唯一区别是我使用的是内连接,而在原始 sql 查询中我使用的是左连接。 有什么方法可以实现这一点,或者我应该使用原始 sql 查询吗?谢谢。

Django ORM:

total=ApplicantInfo.objects.select_related('source_type').values('source_type__source_type').annotate(total_count=Count('source_type'))

在原始 SQL 中输出 DJANGO ORM:

SELECT "applicant_sourcetype"."source_type", COUNT("applicant_applicantinfo"."source_type_id") AS "total_count" FROM "applicant_applicantinfo" INNER JOIN "applicant_sourcetype" ON ("applicant_applicantinfo"."source_type_id" = "applicant_sourcetype"."id") GROUP BY "applicant_sourcetype"."source_type"

原始 SQL:

SELECT source.source_type, count(info.source_type_id) as total_counts from applicant_sourcetype as source LEFT JOIN applicant_applicantinfo as info ON source.id = info.source_type_id GROUP BY source.id

【问题讨论】:

    标签: django postgresql orm


    【解决方案1】:

    如果你想要一个左连接,你不能查询ApplicantInfo。改为查询SourceType

    qs = (SourceType.objects
        .values('source_type')
        .annotate(cnt=Count('applicantinfo'))
        .values('source_type', 'cnt')
    )
    

    由于您尚未发布模型,您可能需要调整字段名称以使其正常工作。

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2021-02-16
      • 2012-09-26
      • 2021-03-28
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 2019-07-02
      相关资源
      最近更新 更多