kramer65
kramer65

Reputation: 53853

Why isn't my Django object saved to the database?

I'm writing tests in a Django project and I've got some factories set up to create test content. I now have some trouble in which an email address isn't saved to the database:

device = DeviceFactory.create()
device.owner.email = '[email protected]'
device.save()

print(device.owner.email)  # prints out '[email protected]'
print(device.id)  # prints out 1
d = Device.objects.get(id=device.id)  # get the object from the DB again
print(d.owner.email)  # prints out [email protected] (or any other mock email address the factory creates)

Why does this not save the record to the database?

Upvotes: 0

Views: 154

Answers (2)

Fomalhaut
Fomalhaut

Reputation: 9727

If you need a simple solution, you should call save of your owner field because it is a different model that contains email.

device.owner.save()

But generally I would recommend you to override your save method of your Device model. So next time you won't have to remember that you must call save for internal fields.

class Device(models.Model):
    ...
    def save(self, *args, **kwargs):
        self.owner.save()
        super().save(*args, **kwargs)
    ...

Upvotes: 0

JPG
JPG

Reputation: 88459

email is associated with your Owner model, not Device model.So, You need to call the save() method of owner, not device

device.owner.email = '[email protected]'
device.owner.save()

Upvotes: 2

Related Questions