4

我有一个非常简单的模型可以工作:

class Badge(models.Model):

    name = models.CharField(max_length=16, help_text="Name for Badge")
    category = models.ForeignKey(BadgeCategory, help_text="Category for badge")
    description = models.CharField(max_length=32, help_text="A brief description")
    file = models.ImageField(upload_to=format_badge_name)

    signals.post_save.connect(create_badge, sender=Badge)

我知道我在 signals.py 中的 create_badge 函数有效。如果我在没有发送者值的情况下发送它,它表示发送者是一个 LogEntry 对象。我想/需要在 post_save 脚本中引用一些实例信息,如下所示:

def create_badge(sender, instance, created, **kwargs):

    from userinfuser.ui_api import UserInfuser
    from django.conf import settings

    if created:
        api_key = settings.API_KEY
        api_email = settings.API_EMAIL

        ui = UserInfuser(api_email, api_key)
        ui.create_badge(instance.category.name, instance.name, instance.description, instance.file.url)

我在哪里可以调用我的 post_save 调用,以便它知道 Badge(我假设这是修复?

谢谢。

4

1 回答 1

11

只需在定义 Badge后将信号与 sender=Badge 连接,测试示例:

from django.db import models
from django.db.models import signals

def create_badge(sender, instance, created, **kwargs):
    print "Post save emited for", instance

class BadgeCategory(models.Model):
    name = models.CharField(max_length=100)

class Badge(models.Model):

    name = models.CharField(max_length=16, help_text="Name for Badge")
    category = models.ForeignKey(BadgeCategory, help_text="Category for badge")
    description = models.CharField(max_length=32, help_text="A brief description")

signals.post_save.connect(create_badge, sender=Badge)

测试外壳会话:

In [1]: category = BadgeCategory(name='foo')

In [2]: category.save()

In [3]: badge = Badge(category=category, name='bar', description='test badge')

In [4]: badge.save()
Post save emited for Badge object
于 2012-05-30T07:38:30.750 回答