2017-03-21 38 views
0

私のアプリケーションで簡単なクエリを実行しようとしましたが、Django ORMがLEFT OUTER JOINを生成するため、結果は間違っています。しかし、私はここでdjangoクエリは、内部結合の代わりにLEFT OUTER JOINを生成します

のJOIN INNERの結果が欲しい、私のモデルの一部である:

class Application(models.Model): 
    """ Une application """ 
    app_name = models.CharField(max_length=20) 
    app_pub_date = models.DateTimeField(auto_now_add=True, editable=True) 


class Event(models.Model): 
    """ Evenement status """ 
    STATUS = (
     ('OK', 'OK'), 
     ('KO', 'KO'), 
     ('DEGRADE', 'DEGRADE'), 
    ) 

    app = models.ForeignKey(Application, on_delete=models.CASCADE) 
    status_start = models.DateTimeField() 
    status_end = models.DateTimeField(null=True, blank=True, editable=True) 
    status_global = models.CharField(max_length=20, choices=STATUS,default='OK') 

私は意味し、「開かれたイベント」(持つすべての「アプリケーション」オブジェクトを取得しようとしましたこの単純なSQLクエリは動作します

select a.app_name from event e, application a where a.id = e.app_id and e.status_end is null; 

私はこのDjangoのコードを書いたのNull 'status_end' の値)を持っているイベント
apps_querysset = Application.objects.filter(event__status_end__isnull=True) 

しかし、このコードはLEFT OUTER JOINを示しています。したがって、返される 'アプリケーション'オブジェクトはたくさんあります。

SELECT "appstat_application"."id", "appstat_application"."app_name", "appstat_application"."app_pub_date", "appstat_application"."app_type_id", "appstat_application"."app_site_id" FROM "appstat_application" LEFT OUTER JOIN "appstat_event" ON ("appstat_application"."id" = "appstat_event"."app_id") WHERE "appstat_event"."status_end" IS NULL 

ご存知ですか?

答えて

1

フィルタに余分な引数を追加して、関連するeventがnullでないことを確認できます。

apps_querysset = Application.objects.filter(event__isnull=False, event__status_end__isnull=True) 
+0

ありがとう@Alasdair !!!これは動作します!理由を理解しようとします... – stockersky

+0

元のクエリでは、Djangoは 'event'がヌルでなく、' event.status_null'がヌルである行、 'event.status_end'がヌルである行を返します。なぜなら' event'無効である。フィルタに余分な引数を追加すると、2番目のケースは除外されます。 – Alasdair

関連する問題