[Django]-Filter JSON field django with greater than, less than and a range using _contains

5👍

So I solved the problem some time ago and a notification remembered me this question. The solution is simple. Yo can create a function that generate a dictionary of parameters to pass to the filter function.
In my project I use json fields to save some data for a product according to the category, so for different categories I create different forms.

Suppose I have a category called computers and I want to filter the products in the category “computers” according to the size of the ram.

dict_of_parameters = {"attributes__ram__gte": 2, "attributes__ram__lte": 8}
items = Product.objects.filter(**dict_of_parameters)  #  The ** operator will pass the dictionary as parameters to the function

Tips:

To generate the dictionary of parameters you have a lot of options. In my case I have a field in the category that contains a dictionary of fields useful to generate items and to filter them. A json field, something like

some_category.attributes = {"fields":
                                   {
                                    "ram":
                                         {
                                          "type": "number",
                                          "filter_by": ["gte", "lte"]
                                         }
                                    "CPU":
                                         {
                                          "type": "select",
                                          "options": ["I3", "I5", "I7"]
                                         }
                                   }
                            }

However you don’t have to save this in a database, you can save it in a json file or whatever you want. From here you can create a function that generate a form from this fields and use it to generate the dictionary to pass to the filter function.

This gives you the flexibility of save data in json format in a Postgre database and filter that data even if you don’t know the name of fields or you create new fields.

4👍

If you are using Postgres and a recent version of Django, this can be done using the the JSONField from contib.postgres.fields:

Item.objects.filter(data__size=12)

Docs: https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#querying-jsonfield

If your queries get more complex, I would use a related model rather than than a JSONField so you can use the ORM.

👤arie

Leave a comment