9

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?

blue_note
  • 27,712
  • 9
  • 72
  • 90

1 Answers1

7

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.

Endre Both
  • 5,540
  • 1
  • 26
  • 31