简体   繁体   English

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

[英]django post_delete() signal handler doesn't work

I am trying to make it so that the 'num_posts' field of a blog object is decremented every time a post belonging to that blog is deleted, and incremented every time a post is created. 我正在尝试使博客对象的“ num_posts”字段在每次删除属于该博客的帖子时减少,并在每次创建帖子时增加。 I was able to implement the overloaded save method easily enough: 我能够很容易地实现重载的save方法:

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()

But for whatever reason, the logic does not work when deleting a Posts object. 但是无论出于什么原因,删除Posts对象时,逻辑都不起作用。 I'm following best practices by using signal handlers in a handlers.py file in a signals submodule. 我正在通过在信号子模块的handlers.py文件中使用信号处理程序来遵循最佳实践。 I then import the submodule in my ready() method in my TasksConfig(Appconfig) method in apps.py 然后我导入我的子模块ready()方法在我TasksConfig(Appconfig)的方法apps.py

I don't seem to be getting any syntax errors, or any errors at all. 我似乎没有任何语法错误,也没有任何错误。 The num_posts field on the relevant blog simply fails to decrement. 相关博客上的num_posts字段无法减少。 Here is the relevant code: 以下是相关代码:

From my handlers.py : 从我的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

From my apps.py : 从我的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

Also, here is the full Posts object in models.py , just in case you guys can see something I'm missing: 此外,这是models.py完整的Posts对象,以防万一你们看到我所缺少的东西:

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()

I suspect that it is something obvious. 我怀疑这很明显。 I'm just at a loss because there doesn't seem to be any error message coming from anywhere. 我很茫然,因为似乎没有任何错误消息来自任何地方。

You forgot to save the updated Blogs instance in handle_bpost_delete 你忘了保存更新Blogs的情况下handle_bpost_delete

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

There's a simpler way to get the count of related objects, though. 不过,有一种更简单的方法来获取相关对象的数量。 You can simply let the database do the count when you need it. 您可以简单地让数据库在需要时进行计数。 Quite fast, and much less error prone. 相当快,而且错误少得多。

Example: 例:

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 https://docs.djangoproject.com/zh-CN/1.11/topics/db/aggregation/#following-relationships-backwards

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM