Bulk delete Django by ids

天涯浪子 提交于 2020-07-20 04:51:22

问题


I writing a project using Django REST Framework, Django and Postgres as a database. I want to bulk delete in one query. So, it is possible to do without writing a query using pure SQL? There is an example, but the count of executet query equal length of a list of ids (for example, if in delete_ids 2 ids, Django will execute 2 queries):

delete_ids = [...]
MyModel.objects.filter(id__in=delete_ids).delete()

回答1:


Not possible using the filter and delete together using raw sql query.

https://docs.djangoproject.com/en/2.1/topics/db/sql/

 MyModel.objects.raw('DELETE FROM my_model WHERE id IN (%s)', [','.join([list_of_ids])])

For fast deletes won't advice but you can also use

 sql.DeleteQuery(MyModel).delete_qs(qs, using=qs.db)



回答2:


jackotyne's answer is incorrect as a DELETE statement cannot be run with django raw. The idea behind django raw is that it returns a queryset, but DELETE won't do that.

Please read the reply to this answer.
You will need a database cursor as stated in the django documentation.

with connection.cursor() as cursor:
    cursor.execute(
        'DELETE FROM "appname_modelname" WHERE id IN (%s)' % ', '.join(delete_ids)
    )

Of course it is better to filter with django and get a queryset and do a bulk delete with queryset.delete(), but that is not always possible depending on the data's logic.



来源:https://stackoverflow.com/questions/51879460/bulk-delete-django-by-ids

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