python - 过滤 Django 查询集的字典值

标签 python django python-3.x django-queryset

我有一个 Products 查询集,其中 JSONField attributes 包含 dict

class Product(models.Model):
attributes = JSONField(
    pgettext_lazy('Product field', 'attributes'),
    encoder=DjangoJSONEncoder, default={})

我想过滤产品,其中attributes['12'] == '31'

以下作品:

qs.filter(attributes__contains={'12': '31'})

以下一项没有:

qs.filter(attributes__12='31') 这是我可以使用 PostgreSQL 实现的目标还是应该将其移至 ES?

编辑: 不幸的是,我无法使用第一个解决方案,因为这个dict可能包含更多键。

第一个解决方案效果很好。鉴于我们有:

product.attributes = {'333': ['6', '1']}

我们可以通过以下方式过滤掉它:

Product.objects.filter(attributes__contains={'333': ['6']}

等等。完全忽略了它。

最佳答案

您应该能够使用第二种格式,即 qs.filter(attributes__key='value')

在本例中您的问题为 explained in the docs ,是当在 JSON 查询中使用整数作为键时,该键将用作数组的索引,因此它被解释为 attributes[12] 而不是 attributes[' 12']

只要坚持使用字符串键,就应该没问题。

一个例子:

class MyModel(models.Model)
    json = JSONField(default=dict)


p = MyModel.objects.create(json={'0': 'something', 'a': 'something else'})

MyModel.objects.filter(json__0='something') # returns empty queryset
MyModel.objects.filter(json__a='something else') # returns the object created above

关于python - 过滤 Django 查询集的字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47541066/

相关文章:

python - 如何在 Python Pandas 中使用 groupby().apply() 而不是在整个数据集上运行循环?

python - 如何删除使用 librosa.display.specshow 创建的图中的 Y 轴标签、刻度线和轴标签

python - zip 密码破解器中的多线程

django - 向呈现的 html 添加了禁用属性,现在表单无效

Python 3 二进制到十六进制(带填充)

python-3.x - Python 3 对象构造 : which is the most Pythonic/the accepted way?

python - 无法从源 pylance 解析导入 flask

Django 休息框架 : DRYer pagination for custom actions

json - ReactJS 和 django 表单

python - 我可以在 python3 中使 pprint 不拆分字符串,就像在 python2 中一样吗?