为什么我的Django对象没有保存到数据库?

时间:2020-02-11 14:06:53

标签: python django django-models orm model

我正在Django项目中编写测试,并且已经建立了一些工厂来创建测试内容。现在,我遇到了一些麻烦,其中电子邮件地址没有保存到数据库中:

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)

有人知道为什么这不将记录保存到数据库吗?欢迎所有提示!

2 个答案:

答案 0 :(得分:2)

email 与您的 Owner 模型相关,而不与 Device 模型相关。因此,您需要调用 save() owner 方法,而不是 device

device.owner.email = 'a@b.c'
device.owner.save()

答案 1 :(得分:0)

如果您需要简单的解决方案,则应调用save字段的owner,因为它是包含email的不同模型。

device.owner.save()

但是通常我建议您覆盖save模型的Device方法。因此,下次您不必记住必须调用save来访问内部字段。

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