【发布时间】:2016-02-21 22:35:23
【问题描述】:
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------|--------true ---------|
|---12---|---------2----------|----1------|--------假--------|
|---22---|------------2----------|-----2-----|--------true ---------|
我使用左连接来获得该结果:
结果:
|-T1.id-|-subs_code-|-subs_name-|-T1.id-|-notification_id-|-user_id-|-push_message-|
|---1----|---系统----|---系统-----|---11--|------------1- ------|---1--------|----true-------------|
|---2----|---广播|---广播--|--12---|------------2-------| ---1-------|----假------------|
|---3----|---not_need-|---not_need--|--null-|---------null--------|---空----|----空-------------|
INNER JOIN 无效有 ((
sqlfiddle
我认为只有原始 sql 才有可能
【问题讨论】:
-
Notification.objects.filter(users__id=1)工作吗? -
很遗憾没有(。我现在创建 sql pastebin 以获得更多帮助
-
您有任何错误吗?还是结果不是你想要的?
-
我需要用现有的查询集左连接。 select_related 没用,我现在试试这个
标签: django django-queryset django-orm