How to update manytomany field in Django?

Note: This code will delete the bad ‘georfe’ author, as well as updating the books to point to the correct author. If you don’t want to do that, then use .remove() as @jcdyer’s answer mentions.

Can you do something like this?

george_author = Author.objects.get(name="George")
for book in Book.objects.filter(authors__name="Georfe"):
    book.authors.add(george_author.id)
    book.authors.filter(name="Georfe").delete()

I suspect that this would be easier if you had an explicit table joining the two models (with the “through” keyword arg) — in that case, you would have access to the relationship table directly, and could just do a .update(id=george_author.id) on it.

Leave a Comment