hint

Querying json data with Django

Rob Moorman

25 november 2022

With the ORM of Django querying data is very powerful but yet accessible. A common scenario is filter on model values, e.g. e-mailaddress:

class NewsletterEntry(models.Model):
  email = models.EmailField()

entries = NewsletterEntry.objects.filter(email__endswith="vicktor.nl")

Doing a lot with forms and saving data on large-scale you might want to use the JSONField for complex structures (e.g. social posts or analytical data). This data field is also very convenient for retrieving particular values from it.

A neat feature developers might not know is that quering this data is also very powerful by making use of the query convention the ORM uses. If we take the code above and save it as json data we have to following model:

class NewsletterEntry(models.Model):
  data = models.JSONField()

Let's save same data with the following json structure:

{
  "first_name": "Rob",
  "last_name": "Moorman",
  "email": "rob@vicktor.nl"
}

We should now be able to query the same entries as initial, but with usage of the JSONField features:

entries = NewsletterEntry.objects.filter(data__email__endswith="vicktor.nl")

Meer updates

Dit is wat we recent hebben gedaan.

Beautiful asserts with your Django Test Client

blog

Beautiful asserts with your Django Test Client

Martijn Jacobs

27 maart 2023

Add Plausible to your Terraform CloudFront distribution

blog

Add Plausible to your Terraform CloudFront distribution

Rob Moorman

2 december 2022

Migrating Wagtail ModelAdmin to the new snippet admin views

blog

Migrating Wagtail ModelAdmin to the new snippet admin views

Rob Moorman

25 november 2022