Django subquery in insert

懵懂的女人 提交于 2019-12-11 19:18:16

问题


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
)

回答1:


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.




回答2:


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
)


来源:https://stackoverflow.com/questions/19686559/django-subquery-in-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!