2016-08-19 79 views
0

我有一個非常簡單的模型在我的models.py這樣的:Django信號用於模型值更改條件?

class Music(models.Model): 
    title= models.CharField(
     max_length=100 
    ) 

    description = models.TextField(
     null=True, 
     blank=True 
    ) 

    def __unicode__(self): 
     return self.name 


class Album(models.Model): 
    musician= models.CharField(
     related_name='musician', 
     max_length=100 
    ) 

    music = models.ForeignKey(
     Music, 
     related_name='music' 
    ) 

    def __unicode__(self): 
     return self.user.username 

在這種情況下,我在signals.py做了一個非常簡單的邏輯來檢查新場(新樂)剛剛添加到相冊中。

Album(musician="someone", music=Music.objects.get(title="something")) #pk=1 
Album.save() 

這樣的:

@receiver(post_save, sender=Album) 
def add_new_album(sender, instance, **kwargs): 
    if kwargs.get('created'): 
     print "new album recently created" 

在其他情況下,我想打,如果現有油田被編輯到新的一個只能回答一個信號:

edit_album = Album.objects.get(pk=1) 
edit_album.music = Music.objects.get(title="something_else") 
edit_album.save() 

的使用post_save接收器使add_new_album()函數在每次編輯現有字段時被觸發。所以我的問題是,應該在signals.py中實現的邏輯是什麼,它只響應editi ng字段的條件?

回答

0

所以我只想在某些領域改變的時候觸發你的信號吧? 您可以使用一個名爲Django Field history

事情是這樣的包:

@receiver(post_save, sender=<sender>, dispatch_uid=<string>) 
def method(sender, instance, **kwargs): 
    last_field_change = FieldHistory.objects.filter(field_name=<your_field_which_you_want_to_check_for_change>, 
              object_id=instance.id).last() 
    if last_field_change: 
     #do your thing