【问题标题】:Why isn't my Django object saved to the database?为什么我的 Django 对象没有保存到数据库中?
【发布时间】:2020-05-26 23:16:38
【问题描述】:

我正在一个 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)

为什么不将记录保存到数据库中?

【问题讨论】:

    标签: python django django-models orm model


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      device.owner.save()
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-21
        • 1970-01-01
        • 1970-01-01
        • 2017-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多