Django insert large queryset into m2m

Django -- Posted on Sept. 11, 2024

Django insert large queryset into m2m

              
                from django.db import transaction

# Retrieve the book instance
book = Book.objects.get(id=1)

# Retrieve the large queryset of authors
large_authors_qs = Author.objects.filter(name__startswith='J')

# Define the chunk size
CHUNK_SIZE = 1000

# Add authors in chunks
with transaction.atomic():
    for i in range(0, large_authors_qs.count(), CHUNK_SIZE):
        chunk = large_authors_qs[i:i + CHUNK_SIZE]
        book.authors.add(*chunk)
                  
   
            

Related Posts