Django: removing item from many-to-many relation m

2020-07-26 07:33发布

问题:

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()