About Querying Items Containing a Specific Value in a JSON Field

To query records by a specific key–value pair inside a nested JSON field, you can convert the value to a string and search it using icontains, like this:

image = MediaImage.objects.get(pk=1)
related_articles = Article.objects.filter(
    content_json__icontains=f'"uuid": "{image.uuid}"'
)

Note that the double quotes and the space matter here.

Tips and Tricks Programming Databases Django 6.x Django 5.2 Django 4.2 PostgreSQL