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

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

No comments:

Post a Comment