Наг*_*мер 1 django django-signals
我正在尝试解决以下问题。我有 django 视图,它提供在数据库中保存对象的功能。查看将保存对象后,我想立即处理保存的对象上的一些逻辑(例如检查某些字段与另一个对象的相似性)
我听说 django 信号特别是关于 post_save 信号,我认为这适合我的用例。但对于我的用例,我需要传递启动 post_save 信号执行的对象 ID。django 中是否存在任何内置解决方案来提取该对象 ID,以进一步将其传递给信号函数的接收者
希望我的伪代码能够提供更多的证明
app_view(receive and save data as django model object)
post_save signal(receiver, id_of_object_initiated_execution)
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以将 post_save 信号与如下代码一起使用。'instance' 参数代表保存的对象。所以'instance.id'将给出对象的id。
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=<YourModel>)
def post_save_function(sender, instance, **kwargs):
object_id = instance.id
"""
the rest of the logic here
"""
Run Code Online (Sandbox Code Playgroud)