AbrahamCoding
AbrahamCoding

Reputation: 830

Set Django JSONField value to a JSON null singleton with the Django ORM

Using a Django JSONField on PostgreSQL, say I have the following model

class Foo(models.Model):
    bar = models.JSONField(null=False)

and I want to set a row to have bar=null where null is a single JSON null value (different to a database NULL value).


I can achieve it through a raw SQL query:

UPDATE "myapp_foo"
SET "bar" = 'null'::jsonb
WHERE "myapp_foo"."id" = <relevant_id>

The closest things I can do in the ORM is

Foo.objects.filter(id=<relevant_id>).update(bar=None)

but Django is interpreting this as a database NULL and I get the following error:

null value in column "bar" violates not-null constraint

or

Foo.objects.filter(id=<relevant_id>).update(bar="null")

but Django (correctly) interprets this as the JSON string "null"


Am I missing something or is this a gap in the ORM functionality?

Upvotes: 0

Views: 860

Answers (1)

AbrahamCoding
AbrahamCoding

Reputation: 830

Update: The Django docs have details about how to do this: https://docs.djangoproject.com/en/dev/topics/db/queries/#storing-and-querying-for-none


I have worked out this can be done with the Django Value class.

from django.db.models import Value

Foo.objects.filter(id=<relevant_id>).update(bar=Value("null"))

Upvotes: 1

Related Questions