简体   繁体   中英

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 = 'a@b.c'
device.save()

print(device.owner.email)  # prints out 'a@b.c'
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 jon.avery@ourcompany.com (or any other mock email address the factory creates)

Does anybody know why this doesn't save the record to the database? All tips are welcome!

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 = 'a@b.c'
device.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM