learning_record_recorddinningroom.room_id可能不是NULL

时间:2013-11-26 17:27:52

标签: python django django-views django-signals

我正在尝试使用Django构建一个可以记录另一个用户的修改历史的模型。此外,当保存父模型时,我使用信号功能来保存历史模型。所有其他模型运作良好。

代码如下:

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可能不为NULL”的信息。我认为它可能是room = models.ForeignKey(DinningRoom)或signal和record_dinningroom()函数中的问题,但无法弄清楚如何修复它。

2 个答案:

答案 0 :(得分:4)

您需要为room设置RecordDinningRoom,因为它不是可选字段,请尝试以下操作:

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

答案 1 :(得分: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()