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

时间:2019-02-04 12:27:51

标签: python django signals django-signals

我有一个模型,每隔几秒钟就会有一个后台任务对其进行更新。 当属性状态的实例更改为 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

2 个答案:

答案 0 :(得分:1)

您应该选择覆盖保存方法而不是信号,因为您的更改仅针对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()

答案 1 :(得分:0)

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

interface Port-channel10

 description ** Uplink to C1 **

 description ** Uplink to C2 **

 description ** Downlink to NetAuto **