Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django jsonfield querying on a value which is an array

I have this model:

class InventoryItem(models.Model):
    size_range = JSONField(null=True)  # JSONField in Django 1.9

I populated following data in it:

InventoryItem.objects.create(size_range={'size': ['S', 'M', 'L']})

But When I do following query:

InventoryItem.objects.filter(size_range__size__contains='S')

I get following error:

django.db.utils.DataError: invalid input syntax for type json
LINE 1: ..._inventoryitem"."size_range" -> 'size' @> 'S' LIMIT ...
                                                         ^
DETAIL:  Token "S" is invalid.
CONTEXT:  JSON data, line 1: S

How do I perform the query correctly using .filter() method? This is the SQL query above .filter() method generates:

'SELECT "app_name_inventoryitem"."id", 
"app_name_inventoryitem"."size_range", FROM 
"app_name_inventoryitem" WHERE 
"app_name_inventoryitem"."size_range" -> \'size\' @> S'

How do I perform the query correctly using .filter() method? Thanks in advance.

like image 717
Amrullah Zunzunia Avatar asked Feb 01 '16 16:02

Amrullah Zunzunia


2 Answers

As mentioned in the documentation that contains operator accepts any JSON rather than just a dictionary of strings. https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#containment-and-key-operations

you can do like the following

InventoryItem.objects.filter(size_range__size__contains=['S'])

This will return the object and if you do something like the following

InventoryItem.objects.filter(size_range__size__contains=['K'])

It will return an empty queryset.

You can do the following also:

InventoryItem.objects.filter(size_range__size__contains=['S', 'M'])

This will return your the object as well.

like image 119
Ahmed Hosny Avatar answered Nov 17 '22 11:11

Ahmed Hosny


I haven't used django in a while, but, could this be what you where looking for?

InventoryItem.objects.filter(size_range__size__contains=['S'])
like image 25
phenxd Avatar answered Nov 17 '22 10:11

phenxd