今天突然发现Django在update一个对象时,执行的sql语句是全属性更新,而不是按需(只更新变更了的属性)更新,请问有没有什么可以优化的办法?
以下代码是在django的shell环境里执行的:
>>> from django.db import connection >>> print connection.queries [] >>> from myproj.msg import Message >>> m = Message.objects.get(id=1) >>> m.title = 'new msg title' >>> m.save() >>> print connection.queries [{'time': '0.002', 'sql': u'SELECT `myproj_msg`.`id`, `myproj_msg`.`creator_id`, `myproj_msg`.`title`, `myproj_msg`.`content` FROM `myproj_msg` WHERE `myproj_msg`.`id` = 1 '}, {'time': '0.001', 'sql': u'SELECT (1) AS `a` FROM `myproj_msg ` WHERE `myproj_msg`.`id` = 1 LIMIT 1'}, {'time': '0.054', 'sql': u'UPDATE `myproj_msg` SET `creator_id` = 1, `title` = 'new msg title' , `content` = 'old content' WHERE `myproj_msg`.`id` = 1 '}]
如上代码所示,其实只是像更新“消息”对象的标题,当django对整个对象的所有属性做了update操作,如果content内容非常大,可能会导致数据库瓶颈, 如果不想绕过django的ORM自己写sql,有没有办法解决这个问题?
微博上的“扇贝网老程序员”回复如下:django1.5 已经解决了, 但是实际上这个不算什么问题,几乎没有什么性能上的优势。如果有大数据反复更新,可以考虑把那个大数据拆出来。https://docs.djangoproject.com/en/dev...
供参考。
Message.objects.filter(id=1).update(title="new title")
多说一句,update能避免race-condition,正常情况下save()
只需要在新建instance时用。