2015-11-19 69 views
0

SQL查詢:
我不能爲這個sql查詢創造Django的查詢集

SELECT * 
FROM "notification_notification" AS T0 
    LEFT JOIN (SELECT * 
      FROM "notification_usernotification" 
      WHERE user_id = 1) AS T 
    ON (T0.id = T.notification_id) 

型號:

class Notification(models.Model): 
    subs_code = models.CharField() 
    subs_name = models.CharField() 
    users = models.ManyToManyField(settings.AUTH_USER_MODEL, 
            through='UserNotification') 

class UserNotification(models.Model): 
    notification = models.ForeignKey(Notification) 
    user = models.ForeignKey(settings.AUTH_USER_MODEL) 
    push_message = models.BooleanField() 

這可能嗎?
我嘗試了各種技術,但我無法在django ORM下創建簡單的sql;

notification_notification表AS T0
| --- id --- | ----- subs_code ----- | ----- subs_name ----- |
| --- 1 ---- | -----系統---------- | ----系統------------ |
| --- 2 ---- | -----廣播------ | -----廣播------- |
| --- 3 ---- | ----- not_need ------- | ----- not_need ------- |

notification_usernotification table AS T1
| --- id --- | -notification_id- | -user_id- | -push_message- |
| --- 11-- | --------- 1 ---------- | ---- 1 ------ | ------- -true --------- |
| --- 12-- | --------- 2 ---------- | ---- 1 ------ | ------- -false -------- |
| --- 22-- | --------- 2 ---------- | ----- 2 ----- | ------- -true --------- |

我使用左側加入了這一結果:
結果:
| -T1.id- | -subs_code- | -subs_name- | -T1.id- | -notification_id- | -user_id- | -push_message- |
| --- 1 ---- | ---- ---系統---- | ---系統----- | --- 11-- | ------------ 1 ------- | --- 1 ------- | ----真------------- |
| --- 2 ---- | ---廣播| ---廣播 - | --12 --- | ------------ 2 -------- - | --- 1 ------- | ----假----------- |
| --- 3 ---- | --- not_need- | --- not_need-- | --null- | --------- null -------- | - --null ---- | ----空------------- |

INNER JOIN是無效的有((
sqlfiddle

我認爲這可能僅適用於原始的SQL

+0

是否ification.objects.filter(users__id = 1)'工作? –

+0

不幸的是(。我現在創建sql pastebin更友好 – madjardi

+0

['select_related()'?](https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-related) –

回答

0
  1. 寫原始SQL查詢
  2. 它通過額外的寫:見here stackoverflow
Notification.objects.extra( 
    select={ 
      'push_message': 
       'SELECT {tbl_1}.push_message::BOOLEAN FROM {tbl_1} ' 
       'WHERE {tbl_1}.notification_id = {tbl_2}.id ' 
       'and {tbl_1}.user_id = %s'.format( 
        tbl_1=UserNotification._meta.db_table, 
        tbl_2=Notification._meta.db_table)}, 
     select_params=(user.id,))