2013-01-24 99 views
6

我有一個models.Model子類,它表示我的mysql數據庫(即managed = False)上的視圖。django防止刪除模型實例

但是,運行我的單元測試時,我得到:

DatabaseError: (1288, 'The target table my_view_table of the DELETE is not updatable')

該刪除請求的來源是(間接)通過外鍵。我已經(簡體):

class MyViewModel(models.Model): 
    problematic_field = models.ForeignKey(ActualTableModel) # specifying on_delete=models.SET_NULL simply replaces the DELETE error with an UPDATE one 

在我的測試,我刪除ActualTableModel實例的刪除,並且看起來Django是繼記錄的行爲:

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

這似乎導致應用於(managed = False)視圖時出現問題。

我試圖重寫刪除方法,以防止刪除:

class MyViewModel(models.Model): 
    ... 
    def delete(self, *args, **kwargs): 
     pass # deletion of a view row is never valid 

但這並沒有解決問題。

如何防止此行爲?

回答

7

也許你可以嘗試其中的各種on_delete argument options

即:

problematic_field = models.ForeignKey(ActualTableModel, on_delete=models.PROTECT) 
+1

感謝您的文檔鏈接。我試過on_delete = models.SET_NULL,但我忽略了DO_NOTHING。後者修復了錯誤。 – sapi