2017-09-12 43 views
2

(使用Django 1.11.5)Django的 - 自定義保存方法模型

傳統,我總是創造像這樣的模型:

class Animal(models.Model): 
    is_hungry = models.BooleanField(default=True) 

然後進行修改,如下所示:

animal = Animal() 
animal.save() 

animal.is_hungry = True 
animal.save() 

最近,我看到一個朋友定義模型與自定義的保存方法:

class Animal(models.Model): 
    is_hungry = models.BooleanField(default=True) 

    def feed_animal(self): 
     self.is_hungry = False 
     self.save() 

並調用這個方法似乎按預期方式工作:

>>> from testapp.models import Animal 
>>> a = Animal() 
>>> a.save() 
>>> a.is_hungry 
True 
>>> 
>>> a.feed_animal() 
>>> a.is_hungry 
False 

有沒有在模型定義定義這種自定義的保存方法什麼好處/缺點?有沒有理由直接在對象上調用.save()

+0

沒有缺點,但將模型的方法隱藏起來可能不是最佳做法。定義只修改模型對象狀態並保存到view.py代碼的feed_animal方法會更清晰。 –

+0

@ Jarek.D - 所以你仍然會推薦保留'feed_animal()'方法,只需刪除'self.save()'? –

+0

是的,但如果feed_animal()只會真正改變屬性的狀態,它不是很pythonic - 只是做a.is_hungry = False –

回答

3

沒有什麼缺點,但隱含在模型方法中的保存可能不是最佳實踐。這將會是清潔的定義,只是修改了模型對象的狀態feed_animal方法和離開節能的view.py代碼:

# model.py 
class Animal(models.Model): 
    is_hungry = models.BooleanField(default=True) 

    def feed_animal(self): 
     # makes sense if ther's more to it than just setting the attribute 
     self.is_hungry = False 

# view.py 
a = Animal() 
a.feed_animal() 
a.save() 

與定義自定義保存方法在Django被理解爲覆蓋保存模式子類中的Model類的方法,並且如果需要在節省時永久地更改對象行爲,則是合理的:

# model.py 
class Animal(models.Model): 
    is_hungry = models.BooleanField(default=True) 

    def feed_animal(self): 
     # makes sense if ther's more to it than just setting the attribute 
     self.is_hungry = False 

    # let say we need to save only well fed animals 
    def save(self, *args, **kwargs): 
     self.feed_animal()   
     super(Model, self).save(*args, **kwargs) 
1

這取決於您的使用情況。

在上面給出的例子中,如果餵食動物,它最終會結束不餓的動物(物體)。因此,在設置self.is_hungry(其中self是對象本身)後,在feed_animal函數中調用self.save以保存對象的最終狀態。

相關問題