2014-10-16 85 views
0

我想更新電子郵件表中所有對象的一個​​布爾字段,但我需要在保存一封電子郵件時執行此操作。我有一個對象命名爲供應商和其他指定的客戶端,既可以有多個電子郵件的,(通過電子郵件/客戶端具有一對多的關係,以電子郵件)這是我的電子郵件型號:DJANGO更新保存表中所有對象的字段

class Email(models.Model): 
    main = models.BooleanField("(Main)", default=False) 
    address = models.CharField("Email address") 

    limit = models.Q(app_label='store', model='store') | models.Q(app_label='core', model='client') 
    content_type = models.ForeignKey(ContentType, 
            limit_choices_to=limit, 
            verbose_name="Related Object Type") 
    object_id = models.PositiveIntegerField(verbose_name="Related Object ID") 
    content_object = GenericForeignKey('content_type', 'object_id') 

    class Meta: 
     app_label = 'info' 

正如你所看到的電子郵件有一個genericforeignkey,因爲它們可以屬於供應商或客戶端模型,主要字段表示該電子郵件是相關對象的主要部分,每個相關對象只有1封電子郵件可以具有main = True。

我的方法是覆蓋保存方法:

def save(self, *args, **kwargs): 

    emails = Email.objects.filter(content_type__pk=self.content_type.id, object_id=self.object_id, main=True) 
    for email in emails: 
     email.main = False 
     email.save() 
    self.main = True 
    super(Email, self).save(*args, **kwargs) 

的問題是: 當我嘗試保存電子郵件我查詢所有的郵件到主字段設置爲false,但我需要保存該對象修改後,它結束再次調用save函數給我錯誤。

有沒有辦法做到這一點沒有無限循環?

回答

1

如何致電update,它只是更新字段,並沒有調用save

def save(self, *args, **kwargs): 

    Email.objects.filter(content_type__pk=self.content_type.id, object_id=self.object_id, main=True).update(main=False) 

    self.main = True 
    super(Email, self).save(*args, **kwargs) 

這裏是documentation on update

+0

尼斯,完美!謝謝 – 2014-10-16 21:48:53