Django 如何在使用信号从另一个模型输入后更新某些特定字段数据

Django How to update some specific fields data after input from another model using signals

我对 Django 信号有一些问题。在将数据输入 PenelitiPemindahanWP 后,我想将 PermohonanWP 状态模型字段从 'PROSES' 更新为 'SUCCESS'。 (假设我已经将数据输入到状态为 'PROSES' 的 PermohonanWP 模型)

这是我的 model.py

class PermohonanWP(models.Model):
      npwp = models.CharField(max_length=15, null=False)
      nama = models.CharField(max_length=100, null=False)
      status = models.CharField(max_length=20, null=True)

class PenelitiPemindahanWP(models.Model):
      permohonan_pemindahan = models.ForeignKey(PermohonanWP, on_delete=models.CASCADE)
      nomor_lhp = models.IntegerField(null=True)
      nomor_st = models.CharField(max_length=50, null=True)

这里是我输入的信号 model.py

@receiver(post_save, sender=PenelitiPemindahanWP, dispatch_uid="update_permohonan_id")
def update_permohonan(sender, instance, **kwargs):
    pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan)
    pemohon.status = "SUCCESS"
    pemohon.save()

我想从 PermohonanWP 更新状态字段,但是每当我提交保存按钮时,它都没有保存,也没有更新字段。

更正这个

pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan)

pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan.id)

甚至简单:

pemohon = instance.permohonan_pemindahan

您需要在 apps config ready method

中导入您的信号

apps.py

from django.apps import AppConfig

class <App_name>Config(AppConfig):
    name = '<app name>'

    def ready(self): 
        import <app name>.signals

init.py

default_app_config = '<app_name>.apps.<App_name>Config'    # first letter capital

你的信号应该是这样的,

@receiver(post_save, sender=PenelitiPemindahanWP, dispatch_uid="update_permohonan_id")
def update_permohonan(sender, instance, **kwargs):
    pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan.id)
    pemohon.status = "SUCCESS"
    pemohon.save()

希望有用。


提示:

如果您在状态字段中使用选项会更好。

In my opinion, whenever it’s possible integers should be used for storing information about some resource status. There is a big advantage of such a solution. After adding a database index to that field, search performance will be more efficient when using an integer field instead of a char field. Another advantage is the fact that we can manipulate ordering in such a field. For example: In the model there is a status field with the allowed choices: New = 1, Draft = 2, Published = 3. If we want to order those Django models instances by status from the new created to published, we can now easily add order on that field (ascending on integer field). ref

一种方法;

models.py

    ...
    # status
    PENDING = 1
    PROCESSING = 2
    DELIVERED = 3
    CANCELED = 4

    ORDER_STATUS = [
        (PENDING, 'Pending'),
        (PROCESSING, 'Processing'),
        (DELIVERED, 'Delivered'),
        (CANCELED, 'Canceled')
    ]

    status = models.PositiveSmallIntegerField(choices=ORDER_STATUS, default=PENDING)
   ...