簡體   English   中英

Django ArrayField 默認應該是可調用的

[英]Django ArrayField Default Should be a Callable

我試圖在我的 django 項目中使用 postgresql ArrayField 將其設置為默認值,但我無法擺脫警告ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, eg use list instead of [] ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, eg use list instead of []

這是我的代碼:

def get_default_subscriptions():
    return 'Noticias, Promociones, Pagos, Compras'.split(', ') # this returns a list
 
class myModel(models.model):
    # other fields
    subscriptions = ArrayField(models.CharField(max_length=200), default=get_default_subscriptions()) # this is a callable, so, why the warning?

文檔是這樣說的: If you give the field a default, ensure it's a callable such as list (for an empty default) or a callable that returns a list (such as a function). Incorrectly using default=[] creates a mutable default that is shared between all instances of ArrayField. If you give the field a default, ensure it's a callable such as list (for an empty default) or a callable that returns a list (such as a function). Incorrectly using default=[] creates a mutable default that is shared between all instances of ArrayField.

你能告訴我我做錯了什么嗎?

使用default=get_default_subscriptions (不帶括號)代替default=get_default_subscriptions()

為了對 Arakkal 的回答進行一些澄清,可調用對象是一個函數或綁定方法。 您傳遞的是函數調用的返回值,而不是函數本身。 您實際上是內聯調用了 get_default_subscriptions 而不是將函數本身提供給 Django,以便它可以在需要時調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM