的型號:的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是我的。我想讓我的父親,但我得到我的孩子(我得到的人,誰有我作爲父親)
非常好(我會用它以後),但我仍然不知道如何獲得父親實例人...任何想法?
究竟是(快速閱讀是錯誤的; D) – 2014-09-19 22:24:28
你什麼讀得快?我只是好奇。儘管如此,我們很快就找到了解決方案。還請檢查你的答案,我編輯了一些錯別字和小的語法錯誤。 – cezar 2014-09-19 22:38:03
首先,我讀了你的答案,沒有找到解決方案(只讀代碼),想念你的解釋,並看到答案沒用。之後,我再讀一遍,但看到了一個很好的解釋 - 所以我刪除了我的可憐答案,並將其標記出來 – 2014-09-20 07:34:05