34👍
If you wan’t to filter your data by one of fields in your array of dicts, you can try this query:
Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])
It will list all Test
objects that have at least one object in actions
field that contains key fixed_key_1
of value foo2
.
Also it should work for nested lookup, even if you don’t know actual indexes:
Test(actions=[
{'fixed_key_1': 'foo4', 'fixed_key_3': [
{'key1': 'foo2'},
]}
}).save()
Test.objects.filter(actions__contains=[{'fixed_key_3': [{'key1': 'foo2'}]}])
In simple words, contains will ignore everything else.
Unfortunately, if nested element is an object, you must know key name. Lookup by value won’t work in that case.
11👍
You should be able to use a __contains
lookup for this and pass queried values as list as documented here. The lookup would behave exactly like ArrayField. So, something like this should work:
Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])
- [Django]-Cannot access django app through ip address while accessing it through localhost
- [Django]-Removing 'Sites' from Django admin page
- [Django]-Django character set with MySQL weirdness
3👍
You can use the django-jsonfield package, I guess it’s already the one you are using.
from jsonfield import JSONField
class Test(TimeStampedModel):
actions = JSONField()
So to search to make a search with a specific property, you can just do this:
def test_filter(**kwargs):
result = Test.objects.filter(actions__contains=kwargs)
return result
If you are using PostgreSQL, maybe you can take advantage of PostgreSQL specific model fields.
PS: If you are dealing with a lot of JSON structure you have maybe to consider using NoSQL Database.
- [Django]-Django/DRF – 405 Method not allowed on DELETE operation
- [Django]-In django, how do I sort a model on a field and then get the last item?
- [Django]-Django.db.utils.ProgrammingError: relation "bot_trade" does not exist