Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: using F() expressions on JSONField?

Tags:

python

django

I have the model

class Product(Model):
    properties = JSONField()

When querying

Product.objects.values('properties__color')

i'm getting the correct result

SELECT product.properties->color FROM product

However, when I'm doing what I thought to be equivalent

Product.objects.values(color=F('properties__color'))

the query that's executed is completely different

SELECT product.properties AS color FROM product

Is this a bug of django's JSONField, or have I misunderstood F() expressions?

like image 511
blue_note Avatar asked Apr 06 '19 15:04

blue_note


1 Answers

You can use a plain values('fieldname__lookup') because values() supports lookups since v2.1:

Product.objects.values('properties__color')

F expressions however do not support lookups; in fact they silently discard them, as evidenced by your example.

When using JSONField transforms, watch out for a bug when the field you're looking for is nested more than one level deep. In the linked question you will also find a solution for using a named annotation if a plain values() is not sufficient.

like image 74
Endre Both Avatar answered Sep 28 '22 06:09

Endre Both