django post_delete()信号处理程序不起作用

时间:2017-08-27 13:22:53

标签: django python-3.x django-signals

我正在努力使博客对象的'num_posts'字段在每次删除属于该博客的帖子时递减,并在每次创建帖子时递增。我能够轻松地实现重载的保存方法:

def save(self, *args, **kwargs):
    '''After saving a new post, increment the num_posts value in the
    relevant blog.'''
    super(Posts, self).save(*args, **kwargs)
    self.blog_id.num_posts += 1
    tmp = self.blog_id
    tmp.save()

但无论出于何种原因,删除Posts对象时逻辑不起作用。我通过在信号子模块中的handlers.py文件中使用信号处理程序来遵循最佳实践。然后,我在ready()

TasksConfig(Appconfig)方法中的apps.py方法中导入子模块

我似乎没有得到任何语法错误或任何错误。相关博客上的num_posts字段无法减少。以下是相关代码:

来自我的handlers.py

from django.db.models.signals import pre_delete
from django.dispatch import receiver
from webcomics.models import Pages, Posts, Blogs

@receiver(pre_delete, sender=Pages)
def handle_page_delete(sender, **kwargs):
    obj = kwargs['instance']

    if(obj != None):
        tmp1 = obj.prev_id
        tmp2 = obj.next_id

    if(tmp1 != None):
        tmp1.next_id = tmp2
        obj.prev_id = None

    if(tmp2 != None):
        tmp2.prev_id = tmp1
        obj.next_id = None


@receiver(pre_delete, sender=Posts)
def handle_bpost_delete(sender, **kwargs):
    obj = kwargs['instance']

    if(obj != None):
        tmp = Blogs.objects.get(pk = obj.blog_id)
        tmp.num_pages = tmp.num_pages - 1

来自我的apps.py

from django.apps import AppConfig

class WebcomicsConfig(AppConfig):
    name = 'webcomics'


class TasksConfig(AppConfig):
    name = 'tasks'
    verbose_name = "Tasks"

    def ready(self):
        import binshellpress.webcomics.signals.handlers

此外,这里是models.py中的完整帖子对象,以防万一你们可以看到我遗漏的东西:

class Posts(models.Model):
    title = models.CharField(max_length=180)
    pub_date = models.DateTimeField('date publishied', default=timezone.now)
    blog_id = models.ForeignKey('Blogs', on_delete=models.CASCADE)
    series_id = models.ForeignKey('Series', on_delete=models.SET_NULL,
                                  blank=True, null=True)

    # Note: Vanilla TinyMCE Integration seems to be working. Need to
    # modify the implementation to handle links, images, etc.
    data = HTMLField()

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        '''After saving a new post, increment the num_posts value in the
        relevant blog.'''
        super(Posts, self).save(*args, **kwargs)
        self.blog_id.num_posts += 1
        tmp = self.blog_id
        tmp.save()

我怀疑它是显而易见的。我只是感到茫然,因为似乎没有来自任何地方的任何错误信息。

1 个答案:

答案 0 :(得分:0)

您忘记将更新后的Blogs个实例保存在handle_bpost_delete

def handle_bpost_delete(sender, instance, **kwargs):
    instance.blog.num_pages -= 1
    instance.blog.save()

但是,有一种更简单的方法来获取相关对象的数量。您可以在需要时简单地让数据库进行计数。非常快,而且更不容易出错。

示例:

from django.db.models import Count

blogs = Blogs.objects.annotate(num_pages=Count('posts'))
print(blogs[0].num_pages) 

https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#following-relationships-backwards