Home > database >  Django: Unable to save the model instance
Django: Unable to save the model instance

Time:12-24

I have models defined like the below:

class Device(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=50)
    owner = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class DeviceReadings(models.Model):
    device = models.ForeignKey(Device, on_delete=models.CASCADE)
    reading = models.FloatField()
    timestamp = models.DateTimeField()

And I am trying to save models like below:

device = Device.objects.get(pk=device_id)
r = DeviceReadings(device_id=device, reading=reading, timestamp=timestamp)
    r.save()

It gives an error that Invalid UUID format. It works if I set device.pk.

I am not so well-versed in Django, unable to understand why the instance is not being saved.

CodePudding user response:

You have given device_id as device instance, it should be id or pk not the instance. Can use any of the following

device = Device.objects.get(pk=device_id)
r = DeviceReadings(device=device, reading=reading, timestamp=timestamp)
r.save()

or

device = Device.objects.get(pk=device_id)
r = DeviceReadings(device_id=device.id, reading=reading, timestamp=timestamp)
r.save()

CodePudding user response:

Try this:

device = Device.objects.get(pk=device_id)
DeviceReadings.objects.create(device=device.id, reading=reading, timestamp=timestamp)

This will create and save object in one step.

  • Related