2017-08-22 37 views
0

我有一個自定義的保存功能,在這裏我想根據這樣的條件來執行某些功能的型號:傳遞kwargs到get_or_create方法在Django

class ClassName(models.Model): 

    def save(self, *args, **kwargs): 
     reindex = **kwargs.pop("reindex") 

     super().save(*args, **kwargs) 

     if reindex: 
      People.objects.create() 

任務裏面現在我想打電話給以下:

kwargs = { "reindex": False} 
ClassName.objects.get_or_create(**kwargs) 

當它一創建,它顯然運行保存功能,但它給我一個錯誤說reindex is not a field。 我一直在研究了一段時間,並不能找出該怎麼做。也許有人可以指出我正確的方向。

我只是想在一個參數傳遞到get_or_create,這樣我可以有條件地保存方法執行特定功能。

謝謝您提前!

回答

1

當你

kwargs = { "reindex": False} 
ClassName.objects.get_or_create(**kwargs) 

它實際上相當於

ClassName.objects.get_or_create(reindex=False) 

因此,由於reindex似乎不是在模型中定義ClassName一個字段,你會得到一個錯誤。


順便說一句,超過該出現錯誤,例如事 reindex = **kwargs.pop("reindex"),你應該定義爲 reindex模型的領域之一。但我承認我盲目回答,因爲對我而言,你的班級定義不能像這樣工作。如果假定reindex是一個整數字段,你可以做

class ClassName(models.Model): 
    reindex = models.IntegerField(null=True) 

    def save(self, *args, **kwargs): 
     super(ClassName, self).save(*args, **kwargs) 
     if "reindex" in kwargs: 
      People.objects.create() 
+0

我明白了!你知道嗎,我可以做些什麼來得到我的解決方案? – Nazariy1995

+0

@ Nazariy1995。嘗試一下。 'makemigrations'和'migrate'。它工作嗎?這是不可能的,因爲我不是你真正想要表現的。 – Kanak

+0

老實說,我最後不得不採用一種完全不同的方式做到這一點不kwargs的用戶。非常感謝你的幫助 – Nazariy1995