{"id":9675,"library":"django-jsonfield","title":"Django JSONField","description":"django-jsonfield provides a robust JSONField for Django models, offering functionality similar to Django's built-in JSONField (introduced in Django 3.1) but with compatibility for older Django versions (2.2+). It supports direct key lookups and queries on JSON data. The library is actively maintained with releases tied to Django compatibility updates and bug fixes. The current version is 1.4.1.","status":"active","version":"1.4.1","language":"en","source_language":"en","source_url":"https://github.com/adamchainz/django-jsonfield","tags":["django","json","database","field","orm"],"install":[{"cmd":"pip install django-jsonfield","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for integration with Django models.","package":"Django","optional":false}],"imports":[{"note":"The internal package name is 'jsonfield', not 'django_jsonfield'.","wrong":"from django_jsonfield.fields import JSONField","symbol":"JSONField","correct":"from jsonfield.fields import JSONField"},{"note":"Django 3.1+ has a built-in JSONField; this library provides its own, distinct implementation.","wrong":"from django.db.models import JSONField","symbol":"JSONField","correct":"from jsonfield.fields import JSONField"}],"quickstart":{"code":"import os\nimport django\nfrom django.conf import settings\nfrom django.db import models\nfrom jsonfield.fields import JSONField # Correct import\n\n# Minimal Django setup for standalone script\nif not settings.configured:\n    settings.configure(\n        DEBUG=True,\n        INSTALLED_APPS=[\n            'myapp', # A dummy app for models\n        ],\n        DATABASES={\n            'default': {\n                'ENGINE': 'django.db.backends.sqlite3',\n                'NAME': ':memory:',\n            }\n        },\n    )\ndjango.setup()\n\nclass MyModel(models.Model):\n    name = models.CharField(max_length=255)\n    metadata = JSONField(default=dict) # Use default=dict for easier creation\n\n    class Meta:\n        app_label = 'myapp' # Required when models are not in a formal app dir\n\n    def __str__(self):\n        return f\"{self.name} (Metadata: {self.metadata})\";\n\n# Simulate migrations for the quickstart\ntry:\n    from django.core.management import call_command\n    from io import StringIO\n    out = StringIO()\n    call_command('makemigrations', 'myapp', stdout=out, stderr=out, verbosity=0)\n    call_command('migrate', 'myapp', stdout=out, stderr=out, verbosity=0)\nexcept Exception as e:\n    print(f\"Warning: Could not run Django migrations simulation: {e}. Attempting manual schema creation.\")\n    # Fallback for environments where call_command is tricky\n    with django.db.connection.schema_editor() as schema_editor:\n        schema_editor.create_model(MyModel)\n\n# Create an instance\ninstance = MyModel.objects.create(\n    name=\"Product A\",\n    metadata={'sku': 'P-001', 'dimensions': {'width': 10, 'height': 20}}\n)\nprint(f\"Created: {instance}\")\n\n# Update JSON data\ninstance.metadata['status'] = 'available'\ninstance.metadata['dimensions']['depth'] = 5\ninstance.save()\nprint(f\"Updated: {instance}\")\n\n# Retrieve and access JSON data\nretrieved = MyModel.objects.get(name=\"Product A\")\nprint(f\"Retrieved SKU: {retrieved.metadata['sku']}\")\n\n# Query JSON data directly (supported by django-jsonfield)\nproducts_with_sku = MyModel.objects.filter(metadata__sku='P-001')\nprint(f\"Found {products_with_sku.count()} product(s) with SKU P-001.\")\n\nproducts_wide = MyModel.objects.filter(metadata__dimensions__width__gt=5)\nprint(f\"Found {products_wide.count()} product(s) with width > 5.\")\n","lang":"python","description":"This quickstart demonstrates how to define a model using `django-jsonfield.JSONField`, create instances with JSON data, update the data, and perform queries directly on the JSON fields. It includes a minimal Django setup for standalone execution."},"warnings":[{"fix":"For new projects on Django 3.1+, prefer `from django.db.models import JSONField`. If upgrading an existing project using `django-jsonfield` to Django 3.1+, plan a careful migration path, potentially involving data migrations, if you wish to switch to the built-in field.","message":"Django 3.1 and newer versions include a built-in `JSONField` (`from django.db.models import JSONField`). `django-jsonfield` provides a distinct implementation for older Django versions (2.2-3.0) or specific features. Be careful not to mix them, as behavior and query methods may differ. If using Django 3.1+, consider the built-in field first unless you have a specific reason for this library.","severity":"gotcha","affected_versions":"All versions of django-jsonfield and Django 3.1+"},{"fix":"Remove `db_index=True` (or `False`) from your `JSONField` definitions in your Django models when upgrading to version 1.0 or later.","message":"The `db_index` parameter was removed from `JSONField` in version 1.0. This parameter was never actually supported by PostgreSQL for JSONB columns and was silently ignored. Using it with `django-jsonfield>=1.0` will raise a `TypeError`.","severity":"breaking","affected_versions":"1.0 and newer"},{"fix":"Always use `from jsonfield.fields import JSONField` for correct import.","message":"The Python package name for the `JSONField` class is `jsonfield`, not `django_jsonfield`. Attempting to import from `django_jsonfield.fields` will result in an `ImportError`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Change your import statement to `from jsonfield.fields import JSONField`.","cause":"You are trying to import `JSONField` from a non-existent module named `django_jsonfield.fields`. The correct internal package name is `jsonfield`.","error":"ImportError: cannot import name 'JSONField' from 'django_jsonfield.fields'"},{"fix":"Remove the `db_index` argument from your `JSONField` definition in your Django model (e.g., change `JSONField(db_index=True)` to `JSONField()`).","cause":"You are attempting to use the `db_index` parameter with `JSONField` from `django-jsonfield` version 1.0 or newer. This parameter was removed because it was not functionally supported by PostgreSQL for JSONB columns.","error":"TypeError: __init__() got an unexpected keyword argument 'db_index'"}]}