在django的jsonfield中查找该值
该模型包含一个jsonfield:在django的jsonfield中查找该值,django,postgresql,jsonfield,Django,Postgresql,Jsonfield,该模型包含一个jsonfield: class MyModel(Model): test_result = JSONField() 要处理的数据是动态的,{'test1':100,'test2':95,'test9':80,…},{'test2':60,'test3':80,'test6':70,…}…… 我想找到“test2”的所有测试结果,并将它们保存到列表中 all_score_of_test2 =[x.test_result['test2'] for x in MyModel
class MyModel(Model):
test_result = JSONField()
要处理的数据是动态的,{'test1':100,'test2':95,'test9':80,…},{'test2':60,'test3':80,'test6':70,…}……我想找到“test2”的所有测试结果,并将它们保存到列表中
all_score_of_test2 =[x.test_result['test2'] for x in MyModel.objects.filter(test_result__has_keys=['test2'])]
它可以工作,但性能不好。有没有更快的方法来完成这项任务?我使用的是postgresql13.1,我建议您创建M2M关系,而不是使用JSONField,因为它可以提供更好的性能
类测试(models.Model):
name=models.CharField(…)#例如test1、test2
类TestResult(models.Model):
测试=型号。外键(测试…)
person=模型。外键(person,…)
分数=模型。小数点(…)
类MyModel(models.Model):
测试结果=模型.ManyToManyField(测试,通过=测试结果,…)
然后您可以通过查询得到test2的分数:
test2的所有分数=TestResult.objects.filter(test\u name='test2')。值列表('score',flat=True)