我有一个 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/