i have 1 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 got '2'.
i need some help :(
CodePudding user response:
use 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
CodePudding user response:
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')
I hope this helps.
Some helpful links: