Creting在Django使用馈送信号(Creting feed using signals in

2019-10-19 03:31发布

在这里,我已经定义了一个模型,以创建“models.py”饲料实例:

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

  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 create:
                si = StreamItem.objects.get_or_create(content_type=ctype, object_id=instance.id, pub_date=pub_date)

# Send a signal on post_save for each of these models
for modelname in [Fest, College, Event]: 
    my_signal = dispatch.Signal()      
    my_signal.connect(create_stream_item, sender=modelname)

那么我创建的视图用于获取,如果我创建一个从管理站点的StreamItem对象,它是工作得很好的饲料。 但是, 信号部分不只是工作。 我只是学习,所以,我不明白的地方我错了。 请帮忙。

Answer 1:

使用post_save信号:

from django.db.models.signals import post_save

for model in [Fest, College, Event]:
    post_save.connect(create_stream_item, sender=model)


文章来源: Creting feed using signals in Django