我无法为此sql查询创建django queryset

时间:2015-11-19 16:48:12

标签: django django-queryset django-orm

sql查询:

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表AS T1
| --- ID --- | -notification_id- | -user_id- | -push_message- |
| --- 11-- | --------- ---------- 1 | ---- ------ 1 | --------真--------- |
| --- 12-- | --------- ---------- 2 | ---- ------ 1 | --------假-------- |
| --- 22-- | --------- ---------- 2 | ----- ----- 2 | --------真--------- |

我使用左连接获得该结果:
结果:
| -T1.id- | -subs_code- | -subs_name- | -T1.id- | -notification_id- | -user_id- | -push_message- |
| --- 1 ---- | ---系统---- | --- -----系统| --- 11-- | ------------ 1- ------ | --- 1 ------- | ----真------------- |
| --- 2 ---- | ---广播| --- broadcast-- | --12 --- | ------------ 2 ------- | --- 1 ------- | ----假----------- |
| --- 3 ---- | --- not_need- | --- not_need-- | --null- | --------- --------空| ---空---- | ----空------------- |

INNER JOIN无效((
sqlfiddle

我认为只有原始sql才有可能

0 个答案:

没有答案