へっぽこびんぼう野郎のnewbie日記

けろけーろ(´・ω・`)!

Djangoで"You can't specify target table 'core_user' for update in FROM clause"がでた

[2017/08/21 追記]
なんじゃこのエラーと思って検索したら自分のブログにたどり着いた

updateだけでなく、delete()する前にシグナルのdisconnectをしていてもなる模様( 'ω')
これ問題なのでは。調べて暇だったらDjangoにPR送るか(´・ω・`)

〜追記ここまで〜

>>> user_ids = User.objects.filter(username__contains='kuroneko').values_list('id', flat=True)
>>> users = User.objects.filter(id__in=user_ids)
>>> users.update(is_active=True)
...
...
...
  File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
    res = self._query(query)
  File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
    rowcount = self._do_query(q)
  File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
    db.query(q)
  File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1093, "You can't specify target table 'core_user' for update in FROM clause")

Solve

>>> user_ids = User.objects.filter(username__contains='kuroneko').values_list('id', flat=True)
>>> user_ids = list(user_ids)
>>> users = User.objects.filter(id__in=user_ids)
>>> users.update(is_active=True)

クエリがそんなに頭よくなかった感じ。