Django insert large queryset into m2m

Django September 11, 2024 python

Django insert large queryset into m2m

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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)