def task_cats_added(sender, instance, action, model, **kwargs): print(action) if action != 'post_add': return todo_by_cat = instance.category.through.objects.filter( todoitem_id=instance.id).prefetch_related() category = Category.objects.all().select_related() for cat_id in todo_by_cat: for cat in category: if cat.id == cat_id.category_id: cat.todos_count += 1 cat.save() # # for cat in instance.category.all(): # slug = cat.slug # new_count = 0 # for task in TodoItem.objects.all(): # new_count += task.category.filter(slug=slug).count() # # Category.objects.filter(slug=slug).update(todos_count=new_count) TodoItem.priority_counter()
def task_cats_removed(sender, instance, action, model, **kwargs): if action != "post_remove": return cat_counter = Counter() for t in TodoItem.objects.all(): for cat in t.category.all(): cat_counter[cat.slug] += 1 for category in Category.objects.all(): if category.slug not in cat_counter: cat_counter[category.slug] = 0 for slug, new_count in cat_counter.items(): Category.objects.filter(slug=slug).update(todos_count=new_count) TodoItem.priority_counter()