2012-03-11 27 views
1

我有相當明顯的一段代碼失敗:Django的模型對象的構造失敗默默

temp = MyModel(
    required_field1 = AnotherModel.objects.filter(name="example1")[0], 
    required_field2 = YetAnotherModel.objects.filter(name="example2")[0], 
) 

的問題是,在此之後,臨時設置爲None!我沒有追蹤,沒有錯誤信息 - 它只是不起作用,並離開Nonerequired_fieldNs (for N=1|2)MyModel中唯一的必填字段。對象​​和YetAnotherModel存在。有沒有人有任何想法,爲什麼它不工作,因爲我想(我的意思是它不構建一個新的對象,由臨時引用)。我不能在這裏粘貼我所有的實際代碼,因爲這是一個公司項目,但如果有疑問 - 請問,我可以解釋一下更多。 編輯: 好吧,我想通了它爲什麼失敗,問題是我試圖從該新構造的對象調用一個方法,並導致它以這種奇怪的方式崩潰。此主題現在可以關閉。

+3

您是否嘗試過打破聲明瞭成片,並檢查一切正常一步一步?因此,在創建模型實例之前,執行兩次ORM查找(並打印每個關於它們的信息,以便知道它的工作原理)。否則,你的確切代碼在'manage.py shell' REPL中失敗了嗎? – 2012-03-11 22:45:06

+0

是的,它甚至在manage.py shell中保持穩定 – 2012-03-12 08:11:48

回答

0

除非required_field1required_field2是外鍵,否則上述代碼將不起作用。

你確定你不是這個意思:

temp = MyModel(
    required_field1 = unicode(AnotherModel.objects.filter(name="example1")[0]), 
    required_field2 = unicode(YetAnotherModel.objects.filter(name="example2")[0]), 
) 

或者:

temp = MyModel(
    required_field1 = AnotherModel.objects.filter(name="example1")[0].some_field, 
    required_field2 = YetAnotherModel.objects.filter(name="example2")[0].some_field, 
) 
+0

它們是ReferenceFields – 2012-03-12 08:11:08

+0

那是什麼?它不是標準的Django字段類型。 – 2012-03-12 10:14:31

+0

這是來自MongoDB的DBRef – 2012-03-12 15:35:12