2

I have one model like this:

class SomeModel(models.Model):
    data = models.JSONField(null=False)

SomeModel's data is like

id:1, data:{'one': ['1', '2', '3'], 'two': ['2', '3'], ...}

id:2, data:{'one': ['1', '2'], 'two': ['2'], ...}

id:3, data:{'one': ['1', '3'], 'two': ['3'], ...}

I want to filter all objects, but I got '2'. How can I fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bhnvx
  • 25
  • 6

2 Answers2

3

Use a JSONB query (read Django document)

result = SomeModel.objects.filter(data__one__contains='2', data__two__contains='2')[:]

Always try to store data in such a way that it is less expensive to retrieve it from the database. Of course, this is not always recommended. Maybe writing is more important than reading in some cases.

If you don't know how many keys are inside the data and you want to check all of them, you have chosen a bad method! It is better to save the data in another way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PersianMan
  • 924
  • 1
  • 12
  • 29
  • thank you! I thought so, too. So I changed the data and saved it! Your answer was very helpful for me. :) – bhnvx Sep 14 '22 at 23:42
0

You can do something like this if you change your JSON data to a dictionary:

data = {
    'one': ['1', '2', '3'],
    'two': ['2', '3'],
    'three': ['1', '3']}
    # You'll probably want to loop through all your different id's

for k, v in data.items():
    if '2' in v:
        # Do something
        # Maybe make an empty dict or list above
        # and add your key and value (or the entire object) to it.
        print('Yes')
    else:
        # Do something else
        print('no')

Some helpful links:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tim-Bolhoeve
  • 189
  • 7