编程语言
首页 > 编程语言> > python – 发送模型中的django post_save调用?

python – 发送模型中的django post_save调用?

作者:互联网

我有一个非常简单的模型:

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调用,以便它知道徽章(我假设这是修复?

谢谢.

解决方法:

在定义徽章后,只需将信号与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)

测试shell会话:

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

标签:python,django,django-models,django-signals
来源: https://codeday.me/bug/20190716/1480814.html