我有一个django应用程序,该应用程序接收JSON文档并将其持久化。问题是JSON可能包含设置为null的键。在这种情况下,django不使用默认值,而是尝试将其设置为None,这由于模型定义而失败。
JSON文档:
{
"meta": {
"type": "Transaction",
"version": "1"
},
"id": "***************************",
"date": "2019-03-25",
"purpose": "Lorem ipsum dolor sit amet, consectetur",
-> "additional_purpose": null,
"amount": "12.34",
"currency": "USD"
}
型号
class Transaction(models.Model):
id = models.CharField(max_length=100, primary_key=True)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
created_at = models.DateTimeField(default=django.utils.timezone.now)
date = models.DateField()
purpose = models.TextField()
-> additional_purpose = models.TextField(blank=True, default='')
amount = models.FloatField()
currency = models.CharField(max_length=3)
class Meta:
get_latest_by = '-id'
ordering = ['-date', '-id']
这将产生以下异常:
django.db.utils.IntegrityError: NOT NULL constraint failed: transaction.additional_purpose
不确定如何处理这种情况。即使将值显式设置为null,我也可以应用默认值吗?