简体   繁体   English

如何使用 post_save 通过 Django 信号填充模型字段?

[英]how to populate a model field via django signals with post_save?

After creating a model object I would like to use a post_save signal to populate another model field in the same object with the ID and other values.创建模型对象后,我想使用post_save信号用 ID 和其他值填充同一对象中的另一个模型字段。

But the real question here is, how do i access the field from the instance?但这里真正的问题是,我如何从实例访问该字段? nothing worked没有任何效果

Example: User creates an object -> id of the object is 93 -> I would like to add #00093 as value of another field in the same object.示例:用户创建一个对象 -> 对象的id是 93 -> 我想添加#00093作为同一对象中另一个字段的值。

models.py模型.py

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)
    summary = models.CharField(max_length=255)

signals.py信号.py

@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, **kwargs):
    instance.designation = "#" + "000" + str(instance.id)
    print("Ticket" + instance.designation + " was created.")

I think you really want to do this:我认为你真的想这样做:

@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, created, **kwargs):
    if created:
        designation = "#" + "000" + str(instance.id)
        Ticket.filter(pk=instance.pk).update(designation=designation)
        print("Ticket" + instance.designation + " was created.")

Explanation:解释:

why use if created : designation is only created once when the new Ticket is created.为什么使用if created :创建新票证时只创建一次指定。 It's not updated every time you save the same object.每次保存同一个对象时它都不会更新。

why use Ticket.objects.filter(..).update(..) : we cannot do instance.save() as it'll then call this post_save again and recursion occurs.为什么使用Ticket.objects.filter(..).update(..) :我们不能做instance.save()因为它会再次调用这个post_save并发生递归。 .update on queryset does not call signals so we're safe. .update on queryset 不会调用信号,所以我们很安全。


If you want to use instance.save you might want to look at how to prevent post_save recursion in django.如果您想使用instance.save您可能需要查看如何防止 Django 中的 post_save 递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM