插入中的 Django 子查询

问题描述 投票:0回答:3

当我尝试插入一些值时,是否可以强制 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
3个回答
3
投票

你绝对不能用

create
来做到这一点。没有可用的 API 可以让您执行此操作,因为这是非常不寻常的用例。你必须退回到原始 sql。


0
投票

即使 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
)

0
投票

使用 Django 3.2 现在这似乎是可能的。

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

这将执行类似的 INSERT 查询

INSERT INTO "communicationlog" (
  "device",
  "date_request",
  "content_obj_id",
  "type_request",
  "type_change"
) VALUES (
  %s,
  (SELECT U0."date_request" FROM "communicationlog" U0 WHERE U0."id" = %s),
  %s,
  %s,
  %s
) RETURNING "communicationlog"."id"'
© www.soinside.com 2019 - 2024. All rights reserved.