我有一个具有以下实现的模型
class MyModel(models.Model):
data = models.JSONField(null=True, blank=True)
我有json格式:
{
"name": "Name",
"irrelevant_list": [],
"items": [
{
"name": "Name 1",
"quantity": 1,
"other_list_of_objects": []
},
{
"name": "Name 2",
"quantity": 2,
"other_list_of_objects": []
}
]
}
我想用quantity
的总和来注释db行(即数量= 3),我尝试了多种方法,仍然没有得到正确的查询。
您可以添加一个名为quantities
CharField的字段,并覆盖clean()
方法从实例中计算数量。如果你想在django admin之外保持一致性,不要忘记覆盖save()
方法来调用full_clean()
方法。像这样
def clean(self):
sum_of_quantities = 0
for item in self.data['items']:
sum_of_quantities += item['quantity']
self.quantities = sum_of_quantities
super(MyModel, self).clean()
def save(self, force_insert=False, force_update=False, *args, **kwargs):
self.full_clean()
instance = super(MyModel, self).save(force_insert, force_update, *args, **kwargs)
return instance