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
是否ification.objects.filter(users__id = 1)'工作? –
不幸的是(。我現在創建sql pastebin更友好 – madjardi
['select_related()'?](https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-related) –