【问题标题】:Django subquery in insert插入中的 Django 子查询
【发布时间】:2013-10-30 15:10:45
【问题描述】:

当我尝试插入一些值时,是否可以强制 django 进行子查询? 这会产生两个单独的查询:

CommunicationLog.objects.create(
    device='asdfasdf', 
    date_request=CommunicationLog.objects.get(pk=343).date_request, 
    content_obj_id=338, type_request=1, type_change=2
)

【问题讨论】:

    标签: django subquery django-orm


    【解决方案1】:

    使用create 绝对不能做到这一点。没有可用的 API 可以让您这样做,因为这是非常不寻常的用例。您必须退回到原始 sql。

    【讨论】:

      【解决方案2】:

      即使 API 不允许你做你想做的事,你仍然可以通过在查询日期时使用 .only 方法来稍微提高性能(我认为这是你的意图):

      CommunicationLog.objects.create(
          device='asdfasdf', 
          date_request=CommunicationLog.objects.only('date_request').get(343).date_request, 
          content_obj_id=338, type_request=1, type_change=2
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-26
        • 2014-05-19
        • 2022-01-21
        • 2014-09-04
        相关资源
        最近更新 更多