Issue
Models look like:
class Book(models.Model):
name = models.TextField(verbose_name='Book Name')
class Author(models.Model):
name = models.TextField(verbose_name='Author Name')
Books = models.ManyToManyField(Book)
Book can have many authors and Author can have written many books
Now,
- There is a list like:
[
{Book_id1:[Author_id1, Author_id2]},
{Book_id2:[Author_id2, Author_id3]},
]
This information is required to be updated in the DB. How can this be done in an efficient way using ORM?
(Currently the DB may have Book_id1 linked with [Author_id1,Author_id3] so the update should be able to add author_id2 and delete author_id3 as well)
Solution
You can make two queries on the many-to-many model:
data = [
{book_id1:[author_id1, author_id2]},
{book_id2:[author_id2, author_id3]},
]
book_ids = [book_id for datum in data for book_id in datum]
BookAuthor = Author.books.through
BookAuthor.objects.filter(book_id__in=book_ids).delete()
BookAuthor.objects.bulk_create([
BookAuthor(book_id=bi, author_id=ai)
for datum in data
for bi, ais in datum.items()
for ai in ais
])
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.