About Querying Items Containing a Specific Value in a JSON Field

When you need to query for records with a certain key and value pair in a nested JSON field, you can convert the field value to a string and search in it with icontains, as follows:

1
2
3
4
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 Development Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL