2013-11-26 131 views
1

我想用Django建立一個模型,可以記錄另一個用戶的修改歷史記錄。另外,當保存父模型時,我使用信號功能來保存歷史模型。所有其他模式運作良好。learning_record_recorddinningroom.room_id可能不是NULL

的代碼如下圖所示:

from control.model import DinningRoom` 

class RecordDinningRoom(models.Model): 
    room = models.ForeignKey(DinningRoom) 

    datetime = models.DateTimeField('recordtime', auto_now=True) 

    TURN_ON_OFF = (
     ('ON', 'On'), 
     ('OFF', 'Off'), 
    ) 

    TEMP = (
     ('HIGH', 'High'), 
     ('MEDIUM', 'Medium'), 
     ('LOW', 'Low'), 
    ) 

    on_off = models.CharField(max_length=2, choices=TURN_ON_OFF) 
    temp = models.CharField(max_length=2, choices=TEMP) 

    #signal function: if a user is created, add control livingroom to the user  
def record_dinningroom(sender, instance, created, **kwargs): 
    #the object which is saved can be accessed with **kwargs 
    dinningroom = instance 
    record = RecordDinningRoom(on_off=dinningroom.on_off, temp=dinningroom.temp) 
    record.save() 
# if created: 
#  RecordLivingRoom.objects.create(user=instance) 
post_save.connect(record_dinningroom, sender=DinningRoom) 

,節省了外鍵模式時,跳轉到錯誤頁面的信息「learning_record_recorddinningroom.room_id未必空」。我認爲這可能是room = models.ForeignKey(DinningRoom)或signal和record_dinningroom()函數中的問題,但無法弄清楚如何解決這個問題。

+0

嘗試'record = RecordDinningRoom(on_off = dinningroom.on_off,temp = dinningroom.temp,room = instance)' – karthikr

+0

是的,那是有效的。謝謝。 – noben

回答

4

您需要設置roomRecordDinningRoom,因爲它不是一個可選字段,試試這個:

record = RecordDinningRoom(
    on_off=dinningroom.on_off, 
    temp=dinningroom.temp, 
    room=instance 
) 
1

你必須通過room參數創建RecordDinningRoom記錄

class RecordDinningRoom(models.Model): 
    room = models.ForeignKey(DinningRoom) # !!!! 

這裏:

record = RecordDinningRoom(room=dinningroom, on_off=dinningroom.on_off, temp=dinningroom.temp) 
record.save() 
+0

它應該是'房間=實例'而不是'dinningroom' – karthikr

+0

@karthikr來自問題代碼:dinningroom = instance – ndpu

相關問題