使用post_delete信号删除StreamItem

时间:2013-12-26 12:39:31

标签: python django django-models signals

这是我创建的用于创建新闻Feed的模型。只要创建了模型Fe和事件的实例,就会使用post_save()信号创建 StreamItem 。一切正常。现在我想删除任何 StreamItem 的实例,只要在post_delete()信号中删除Fe和Event的实例。有可能吗?

class StreamItem(models.Model):
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 pub_date = models.DateTimeField()
 user = models.ForeignKey(User)

 content_object = generic.GenericForeignKey('content_type', 'object_id')

def get_rendered_html(self):
    template_name = 'streams/stream_item_%s.html' % (self.content_type.name)
    return render_to_string(template_name, { 'object': self.content_object }) 

def create_stream_item(sender, instance, signal, *args, **kwargs):
# Check to see if the object was just created for the first time
 if 'created' in kwargs:
    if kwargs['created']:
        create = True

        # Get the instance's content type
        ctype = ContentType.objects.get_for_model(instance)

        pub_date = instance.pub_date

        if ctype.name == "photo":
            user = instance.album.user
        else:
            user = instance.user

        if create:
            StreamItem.objects.get_or_create(content_type=ctype, object_id=instance.id, pub_date=pub_date, user = user)

def delete_stream_item(sender, instance, signal, *args, **kwargs):
  instance.delete()

# Send a signal on post_save for each of these models
for model in [Fe, Event ]:
    post_save.connect(create_stream_item, sender=model)
    post_delete.connect(delete_stream_item, sender=model)

1 个答案:

答案 0 :(得分:1)

delete_stream_item()函数中,instance是刚刚删除的对象,在您的情况下是FeEvent实例。你想要的是检索所有相关的StreamItem实例(使用instance ctype和pk)并删除它们。

警告:未经测试的代码:

def delete_stream_item(sender, instance, signal, *args, **kwargs):
    ctype = ContentType.objects.get_for_model(instance)
    StreamItem.objects.filter(content_type=ctype, object_id=instance.id).delete()