I have the follow models:
class Category(models.Model):
....
posts = models.PositiveIntegerField(_('numero post'), default=0)
....
class Post(models.Model):
....
categories = models.ManyToManyField(Category, blank=True, verbose_name=_('categorie'))
....
the Category.posts field counts the number of the posts related to it's own category. I increase the counter into the CreateView in the following way:
class CreatePostView(LoginRequiredMixin, CreateView):
model = Post
...
def form_valid(self, form, **kwargs):
...
categories = self.object.categories.all()
for category in categories:
category.posts = category.posts + 1
category.save()
self.object.save()
return super(CreatePostView, self).form_valid(form)
Whene i delete the blog post i need to decrement the counter when the Post is deleted. I've tried to do in this way:
class DeletePostView(LoginRequiredMixin, DeleteView):
model = Post
...
def form_valid(self, form, **kwargs):
...
categories = post.categories.all()
for category in categories:
if (category.posts - 1) > 0:
category.posts = category.posts - 1
category.save()
return post
But it doesn't work, because the record is deleted before that this method is called.
How can i do this operation before that the record is deleted?
Or there is a built-in way to get the number of related records from Category?