我想用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()函數中的問題,但無法弄清楚如何解決這個問題。
嘗試'record = RecordDinningRoom(on_off = dinningroom.on_off,temp = dinningroom.temp,room = instance)' – karthikr
是的,那是有效的。謝謝。 – noben