0
我想在更新(已經存在的)對象後執行一些操作(發送電子郵件)。 爲了做到這一點,我需要在保存之前和之後比較對象的值,只有當特定的內容發生變化時才執行該操作。從閱讀其他相關問題,我明白,我只能在預存信號中做到這一點,因爲我無法在'後保存'內獲取舊版本,但是 - 如果保存和項目將會出現問題會怎樣不被保存?在這種情況下,我不想執行此操作。所以我想通過重寫視圖保存來以某種方式實現它,但我不確定這是做到這一點的正確方法。你怎麼看? 這在實施前節省:Django - 預保存後保存VS視圖保存
@staticmethod
@receiver(pre_save, sender=Item)
# check if there is change that requires sending email notification.
def send_email_notification_if_needed(sender, instance, raw, *args, **kwargs):
try:
# if item just created - don't do anything
pre_save_item_obj = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed
else:
# check if state changed to Void
if pre_save_item_obj.state_id != VOID and instance.state_id == VOID:
content = {"item_name": instance.title, "item_description": instance.description}
EmailNotificationService().send_email("item_update"
["[email protected]"], str(instance.container.id) +
str(instance.id) + " changed to Void",
content)
你所說的這條線'會不會有什麼問題,一些與節能和項目意味着將不會被saved'如果沒有在你的預存處理程序中引發異常,那麼我不認爲有可能出現問題 –
@ArpitSolanki實際存儲可能出錯的可能性很大!幸運的是,如果你從來沒有從你的數據庫中獲得「IntegrityError」,例如違反了獨特的限制或類似的? – schwobaseggl
IntegrityError是你自己的錯誤。如果你採取了很好的反制措施,那麼它很容易避免。 @schwobaseggl –