Askar Kopbayev
Askar Kopbayev

Reputation: 71

'save() prohibited to prevent data loss due to unsaved related object' even when parent object is saved

Having issues with saving an object to DB. I read other similar posts and still can't understand why it fails because I do save the Monitor object before saving State.

What am I missing here?

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})

Update - added Models:

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

Upvotes: 1

Views: 1973

Answers (1)

Jonah
Jonah

Reputation: 737

Just remove the id field from the Monitors model. Django will create this field automatically and your problem will disappear.

https://docs.djangoproject.com/en/3.0/topics/db/models/#automatic-primary-key-fields

You want an AutoField which is different from an integer field with auto_create=True. That's an advanced feature you probably shouldn't be using.

https://docs.djangoproject.com/en/2.1/howto/custom-model-fields/

Upvotes: 3

Related Questions