如果模型实例字段等于 inplay,如何 运行 函数(Django)

How to run function if model instance field is equal to inplay (Django)

我有一个模型,每隔几秒就会由后台任务更新一次。 我想在属性状态实例变为inplay

时执行一个函数

我已查看文档和示例,但找不到我要查找的内容。在模型实例字段更改为之后,信号是否是调用函数的最佳选择 inplay'?

from django.db import models

class testModel(models.Model):     
    player1 = models.CharField(null=True, max_length=50)
    player2 = models.CharField(null=True, max_length=50)
    Player1_odds = models.FloatField(null=True)
    Player2_odds = models.FloatField(null=True)
    status = models.CharField(null=True, max_length=10)
    complete = models.CharField(null=True, max_length=10)

 from django.dispatch import receiver
 from django.db.models.signals import pre_save, pre_delete, post_save, 
 post_delete
 from django.dispatch import receiver


@receiver(post_save, sender=testModel)
def post_save(sender, instance, created, **kwargs):
    # if status is = inplay call  send
    #
    #
         pass
 def send()
   # run bet

是的,您可以为此使用信号。在您的情况下,您可以从实例中获取更新状态。

@receiver(post_save, sender=testModel)
def post_save(sender, instance, created, **kwargs):
    if instance.status == 'inplay':
       send()

您应该选择覆盖保存方法而不是信号,因为您的更改仅针对 testModel。所以这就是你将如何覆盖保存方法:

class testModel(models.Model): 
     status = models.CharField(null=True, max_length=10)          
     # your other model fields
     def save(self):
         super(testModel, self).save() # this will save model
         if self.status == 'inplay':# this will check if the status is "inplay" after change
            send()