【问题标题】:How to print the kwargs of django signal?如何打印 django 信号的 kwargs?
【发布时间】:2021-01-04 18:16:03
【问题描述】:

我正在从模型发送信号,接收器确实收到了信号,但我无法使用信号中的 kwargs。如何查看/打印信号中发送的内容?

import django.dispatch

timesheet_signal = django.dispatch.Signal()

def send_timesheet_signal(self, employee, employee_id):
        timesheet_signal.send_robust(sender=self.__class__, employee=employee, employee_id=employee_id)

@receiver(post_save, sender=Timesheet)
def update_employee_info(sender, instance, created, **kwargs):
    instance = kwargs.get('instance')
    employee    = instance.employee 
    employee_id = instance.employee_id 
    if created:
         ...

我尝试了很多形状和形式,这是接收器的当前状态。如何查看/打印信号中发送的内容?

【问题讨论】:

  • print(kwargs)?

标签: python-3.x django django-models signals


【解决方案1】:

kwargs 可以被认为是一本字典,你可以通过多种方式解决这个问题。

for k, v in kwargs.items():
    print(f'{k}={v}')

print(kwargs)

一些文档: django.db.models.signals.pre_init

q = Question(question_text="What's new?", pub_date=timezone.now())

发送到 pre_init 处理程序的参数是:

Argument    Value

sender  Question (the class itself) args    [] (an empty list      because there were no positional arguments passed to __init__())

kwargs  {'question_text': "What's new?", 'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)}

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 2019-11-08
    • 2015-09-02
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多