2017-08-09 60 views
-1

我不能復位我初始化默認值。復位模式__init__ get_field()。默認

我有一個模型蒙山選擇,並沒有默認值。 我有兩個使用init默認模型的代理模型。

class Test(models.Model): 
    CHOICE_LIST = ((1, 'Choice1'),(2, 'Choice2') 
    type_test = models.CharField(choices=CHOICE_LIST, max_length=1) 

class Test1Manager(models.Manager): 
    def get_queryset(self): 
     return super(Test1Manager,self).get_queryset().filter(type_test='1') 

class Test2Manager(models.Manager): 
    def get_queryset(self): 
     return super(Test2Manager,self).get_queryset().filter(type_test='2') 

class test1(Test): 
    objects = Test1Manager() 
    class Meta : 
     proxy = True 

    def __init__(self, *args, **kwargs): 
     self._meta.get_field('type_test').default = '1' 
     super(Test1, self).__init__(*args, **kwargs) 

class test2(Test): 
    objects = Test2Manager() 
    class Meta : 
     proxy = True 

    def __init__(self, *args, **kwargs): 
     self._meta.get_field('type_test').default = '2' 
     super(Test2, self).__init__(*args, **kwargs) 

在admin中,當我添加Test1的實例時,type_test的值爲1,正如我所料。 當我添加Test2的一個實例時,該值也是正確的,默認值爲2.

但是當我添加一個Test實例時,該字段的默認值是最後一個打開的。 事實上,如果在我打開test2_admin之前,測試中字段的默認值將是2.

所以我想重置測試模型上該字段的默認值。

我試圖設置默認=無,但在這種情況下,選擇場只顯示值1和2中,沒有空值,所以默認,此字段的值將是第一個。

感謝您的幫助,因此很抱歉我的英文不好:)

+0

如果您向「CHOICE_LIST」添加空白選項,該怎麼辦?例如,看到這裏:https://stackoverflow.com/questions/37223688/django-empty-label-in-choice-field-no-queryset –

回答

0

所以我一直在努力,在默認情況下爲我的課測試空值添加到我的choice_list並進行設置。

如果我將它添加到我的字段中,則沒有任何反應,因爲我的代理的init會覆蓋默認值。 但如果我添加它在我的課初始化,而不是重置價值這個類,這種復位所有代理類的值。也許是因爲代理類繼承了父代init

所以這是不可能的分配缺省值,代理如果父類有自己的缺省值。