【问题标题】:Saving Django Model with OneToOne Relationship Field returns Object has no attribute 'id' error使用 OneToOne 关系字段保存 Django 模型返回 Object has no attribute 'id' 错误
【发布时间】:2018-11-20 06:30:04
【问题描述】:

我在模型 b 和模型 a 中定义了 OneToOne 关系。当我尝试保存模型 b 时,我得到“模型 B:对象没有属性 'id'”错误。如何解决这个问题?我在这里想念什么。

型号:

class ModelA:
  invoicedate = models.DateTimeField(blank=True)
  amount = models.DecimalField(max_digits=12, decimal_places=2)
  status = models.CharField(max_length=20, default='ACTIVE')

  class Meta:
    db_table = "modela"

class ModelB:
  rel = models.OneToOneField(ModelA, on_delete=models.CASCADE, primary_key=True)
  field1 ...

class Meta:
    db_table = "modelb"

将数据插入模型的方法:

@transaction.atomic
def methodToInsertData(args):
   new_modela = ModelA(
                  "invoicedate" = "2018-11-05",
                  "amount" = 5000,
                  "status" = "ACTIVE"
                )
    new_modela.save()

   new_modelb = ModelB(
                 rel = new_modela,
                 ...
                )
   new_modelb.save() #This statement throws "object has no attribute id" error

ModelA 将自动创建 id 作为主键,但 Model B 不会将 id 作为主键,而 rel 字段将是与 Model A 具有 OneToOne 关系的主键。

任何解决此问题的建议将不胜感激。

【问题讨论】:

  • 根据您的代码,您应该无法保存ModelA,您应该遇到SyntaxError: keyword can't be an expression错误
  • 这只是一个日期字段的参考。我现在已将其编辑为 InvoiceDate。

标签: django django-models


【解决方案1】:

可能是您将 OneToOneField 设置为模型的主键。尝试删除 primary_key=True 并将另一个字段(uuid 或整数)显式设置为 pk,或者简单地允许模型设置自己的 id。

  rel = models.OneToOneField(ModelA, on_delete=models.CASCADE)

【讨论】:

  • Model B的rel是​​Model A的扩展,rel key必须是主键。
猜你喜欢
  • 2023-02-22
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 2018-11-03
  • 2022-11-20
  • 2022-12-01
相关资源
最近更新 更多