- book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
- list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
+ old_shelves = list(book.tags.filter(category='set'))
+ new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
+
+ for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
+ shelf.book_count -= 1
+ shelf.save()
+
+ for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
+ shelf.book_count += 1
+ shelf.save()
+
+ book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))