【发布时间】: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