【问题标题】:look up the value in jsonfield of django在 django 的 jsonfield 中查找值
【发布时间】:2021-05-16 07:34:09
【问题描述】:

模型包含一个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.objects.filter(test_result__has_keys=['test2'])]

它可以工作,但性能不好。有没有更快的方法来完成任务?我正在使用 postgresql13.1

【问题讨论】:

    标签: django postgresql jsonfield


    【解决方案1】:

    我建议您创建 M2M 关系而不是使用 JSONField,因为它可以为您提供更好的性能。

    class Test(models.Model):
        name = models.CharField(...)  # such as test1, test2
    
    
    class TestResult(models.Model):
        test = models.ForeignKey(Test, ...)
        person = models.ForeignKey(Person, ...)
        score = models.DecimalField(...)
    
    
    class MyModel(models.Model):
        test_results = models.ManyToManyField(Test, through=TestResult, ...)
    

    那么就可以通过查询得到test2的分数了:

    all_score_of_test2 = TestResult.objects.filter(test__name='test2').values_list('score', flat=True)
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2022-11-30
      • 2021-02-18
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多