Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 636 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to perform filtering with a Django JSONField?

#1
I'm using PostgreSQL and this new field from Django 1.9, JSONField. So I got the following data:

id|data
1 |[{'animal': 'cat', 'name': 'tom'}, {'animal': 'dog', 'name': 'jerry'}, {'animal': 'dog', 'name': 'garfield'}]

I'm trying to figure out how to filter in this list of json.

I tried something like `object.filter(data__contains={'animal': 'cat'}` but I know this is not the way.

Also I've been thinking in get this value and filter it in my code:

[x for x in data if x['animal'] == 'cat']
Reply

#2
As per the Django [JSONField docs][1], it explains that that the `data` structure matches python native format, with a slightly different approach when querying.

If you know the structure of the JSON, you can also filter on keys as if they were related fields:

object.filter(data__animal='cat')
object.filter(data__name='tom')
By array access:

object.filter(data__0__animal='cat')

Your [contains][2] example is almost correct, but your data is in a list and requires:

object.filter(data__contains=[{'animal': 'cat'}])


[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through