在将对象保存到数据库时遇到问题。我读过其他类似的文章,但仍然无法理解它为什么失败,因为我确实在保存状态之前保存了监视器对象
我错过了什么
monitor = Monitors(
hostname=form['hostname'],
type = form['type'],
interval = form['interval'],
ftt = form['ftt'],
alert_type = form['alert_type'],
alert_enabled = form['alert_enabled'],
params = params)
try:
monitor.save()
state = States(monitor=monitor, state=2)
state.save()
except Exception as err:
return render(request, 'error.html', {'error': err})
更新-新增型号:
class Monitors(models.Model):
id = models.IntegerField(primary_key=True, unique=True, auto_created=True)
hostname = models.CharField(max_length=100)
type = models.CharField(max_length=100)
interval = models.IntegerField()
ftt = models.IntegerField()
alert_type = models.CharField(max_length=100)
alert_enabled = models.BooleanField()
params = models.CharField(max_length=1000)
class Meta:
db_table = 'MONITORS'
unique_together = ('hostname', 'type',)
def __str__(self):
return self.hostname
class States(models.Model):
monitor = models.OneToOneField(Monitors, primary_key=True, on_delete=models.CASCADE, )
state = models.IntegerField()
class Meta:
db_table = 'STATES'
def __str__(self):
return self.state
只需从
Monitors
模型中删除id
字段。Django将自动创建此字段,您的问题将消失https://docs.djangoproject.com/en/3.0/topics/db/models/#automatic-primary-key-fields
您需要一个
AutoField
,它不同于带有auto_create=True
的整数字段。这是一个您可能不应该使用的高级功能https://docs.djangoproject.com/en/2.1/howto/custom-model-fields/
相关问题 更多 >
编程相关推荐