0

I'm using Django 2.1 and I have model with JSONField(record):

{
    'fields': [
        {'tag': 'x','value': '12345'},
        {'tag': 'y','value': '67890'}
    ]
}

To query exact 'value' I use:

Data.objects.filter(record__fields__contains=[{'tag':'x', 'value': '12345'}])

My question is, how to use regex with 'value'? e.g.

Data.objects.filter(record__fields__contains=[{'tag':'x', 'value': '/^123.*/'}])
SvartUlv
  • 1
  • 1
  • This will *not* always work, since the order of JSON keys is (conceptually speaking) free, it is possible that the JSON looks like `{"value": '1234', "tag": 'x'}`. As far as I know only PostgreSQL (and MongoDb) have tooling to look into the keys/values in a query. – Willem Van Onsem Sep 24 '18 at 10:44
  • I forgot to mention that I use PostgreSQL:`from django.contrib.postgres.fields import JSONField` I know it's possible in Mongo with raw query: `{ : { $regex: 'pattern', $options: '' } }` – SvartUlv Sep 25 '18 at 15:48
  • could we use `Data.objects.filter(record__fields__regex=r(...)` ? – xjlin0 May 30 '22 at 14:55

1 Answers1

-1

you can simple:

Data.objects.filter(record__icontains='{"tag":"x", "value": "123')

see answer

  • Can you explain your solution? It will be more useful for the community. See How to create a Minimal, Complete, and Verifiable example --> https://stackoverflow.com/help/mcve – Yulio Aleman Jimenez Nov 29 '18 at 14:58