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?
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.
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