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.
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.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With