Django: removing item from many-to-many relation more efficiently

不羁岁月 提交于 2019-12-06 11:09:13

问题


My book class uses a many-to-many field to save its readers. If I want to remove a reader from some books, I can use a loop to go through all book objects to remove the reader. But it's too slow. Is it possible to do it in a bulk operation?

class Book(models.Model):
    readers = models.ManyToManyField(User, related_name='books')

#Remove reader 'foo' from book 1, 2, 3, 4, 5. However, it is slow.
for book in Book.objects.filter(id__in=[1, 2, 3, 4, 5])
    book.readers.remove(R)

回答1:


Yes. You can access the underlying M2M model using the through attribute, and then use that model to do a delete in one query.

Book.readers.through.objects.filter(book_id__in=[1, 2, 3, 4, 5], 
                                    user_id=foo_user)
                            .delete()


来源:https://stackoverflow.com/questions/26839115/django-removing-item-from-many-to-many-relation-more-efficiently

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