【问题标题】:I can't create django queryset for this sql query我无法为此 sql 查询创建 django 查询集
【发布时间】: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


【解决方案1】:
  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,))  

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2019-09-21
    • 1970-01-01
    • 2018-02-01
    • 2013-07-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多