2014-09-19 18 views
0

的型號:的ModelForm實例與ForeignKey的 - 意外行爲

class Person(Models.model): 
    name = models.CharField(max_length=50) 
    father = models.ForeignKey('Person', related_name="father", null=True, blank=True) 
    mother = models.ForeignKey('Person', related_name="mother", null=True, blank=True) 

的形式爲:

class MyForm(ModelForm): 
    def __init__(self, *args, **kwargs): 
    super(MyForm, self).__init__(*args, **kwargs) 
    instance = getattr(self, 'instance', None) 
    if instance and instance.pk: 
     if instance.name !='': 
     self.fields['name'].widget.attrs['readonly'] = True 

     logger.debug("father %s" % instance.father.all()) 

    class Meta: 
    model = Person 
    fields = ('name') 

我的目的是檢查實例有一個父親,所以我加logger.debug,看什麼是在instance.father.all()(我不確定它是否是「或」或其他)。

當我查看日誌時,我看到instance.father.all()不是實例人的父親,而是父親的人是實例Person!

澄清:我們假設,那個Person是我的。我想讓我的父親,但我得到我的孩子(我得到的人,誰有我作爲父親)

非常好(我會用它以後),但我仍然不知道如何獲得父親實例人...任何想法?

回答

1

在下面一行:

logger.debug("father %s" % instance.father.all()) 

調用相關的名稱father,你自然會得到這個人的所有兒童。

將相關名稱更改爲別的,也許fathers_childrenmothers_children,這樣你就不會感到困惑。

如果你想得到一個人的父親,例如當前Person類的實例,您應該嘗試以下行:

logger.debug("father %s" % instance.father) 

這將返回一個對象。

你也可以這樣做:

logger.debug("father %s" % instance.father_id) 

得到父親的ID。

一些好的是格式化字符串這樣的:

logger.debug('father {0}'.format(instance.father)) 

一個孩子只能有一個父親,一個母親,但父親(或母親)可以有許多兒童。所以調用類似instance.father.all()沒有什麼意義。這就像得到孩子的所有父親,只有一個。

+0

究竟是(快速閱讀是錯誤的; D) – 2014-09-19 22:24:28

+0

你什麼讀得快?我只是好奇。儘管如此,我們很快就找到了解決方案。還請檢查你的答案,我編輯了一些錯別字和小的語法錯誤。 – cezar 2014-09-19 22:38:03

+0

首先,我讀了你的答案,沒有找到解決方案(只讀代碼),想念你的解釋,並看到答案沒用。之後,我再讀一遍,但看到了一個很好的解釋 - 所以我刪除了我的可憐答案,並將其標記出來 – 2014-09-20 07:34:05