Django subquery in insert

2019-09-05 23:27发布

Is it possible to force django to make a subquery when I try to insert some values? This produces two separate queries:

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

2条回答
一夜七次
2楼-- · 2019-09-06 00:00

You definitely cannot do it by using create. There's no available API that will let you do it, since this is very unusual use case. You have to fall back to raw sql.

查看更多
混吃等死
3楼-- · 2019-09-06 00:02

Even if the API won't let you do what you want, you can still improve the performance a little bit (which I assume is your intention) by using the .only method when querying the date:

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
)
查看更多
登录 后发表回答