Title: Django: invalid `VectorField` input raises `ValueError` / `DataError` instead of a validation error · Issue #171 · pgvector/pgvector-python · GitHub
Open Graph Title: Django: invalid `VectorField` input raises `ValueError` / `DataError` instead of a validation error · Issue #171 · pgvector/pgvector-python
X Title: Django: invalid `VectorField` input raises `ValueError` / `DataError` instead of a validation error · Issue #171 · pgvector/pgvector-python
Description: Hi @ankane, thanks for pgvector-python! When a VectorField gets malformed input through a ModelForm (including the admin) or a DRF ModelSerializer, the error isn't a validation error. With a non-numeric element, form.is_valid() raises Va...
Open Graph Description: Hi @ankane, thanks for pgvector-python! When a VectorField gets malformed input through a ModelForm (including the admin) or a DRF ModelSerializer, the error isn't a validation error. With a non-nu...
X Description: Hi @ankane, thanks for pgvector-python! When a VectorField gets malformed input through a ModelForm (including the admin) or a DRF ModelSerializer, the error isn't a validation error. With a no...
Opengraph URL: https://github.com/pgvector/pgvector-python/issues/171
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Django: invalid `VectorField` input raises `ValueError` / `DataError` instead of a validation error","articleBody":"Hi @ankane, thanks for pgvector-python!\n\nWhen a `VectorField` gets malformed input through a `ModelForm` (including the admin) or a DRF `ModelSerializer`, the error isn't a validation error. With a non-numeric element, `form.is_valid()` raises `ValueError`. With the wrong number of dimensions, the form or serializer is valid and `save()` raises `DataError` from Postgres. Either way the request ends in a 500 instead of a form error or a 400 response.\n\nDjango's [custom fields docs](https://docs.djangoproject.com/en/6.0/howto/custom-model-fields/#converting-values-to-python-objects) say `to_python()` should raise `ValidationError` when it can't convert a value. `VectorField.to_python` passes the string to `Vector._from_text`, and `float()` raises `ValueError`. For comparison, with `ArrayField(FloatField())` the same kind of input gives a `ValidationError`: the model field rejects `'[\"1\", \"x\"]'`, and its form field rejects `'1,2,x'` with \"Item 3 in the array did not validate\".\n\n`HalfVectorField` and `SparseVectorField` raise `ValueError` for malformed strings in the same way.\n\n### Reproduction\n\n```python\nimport django\nfrom django.conf import settings\n\nsettings.configure(\n DATABASES={'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pgvector_python_test'}},\n INSTALLED_APPS=[],\n)\ndjango.setup()\n\nfrom django import forms\nfrom django.db import connection, models\nfrom pgvector.django import VectorField\nfrom rest_framework import serializers\n\n\nclass Item(models.Model):\n embedding = VectorField(dimensions=3)\n\n class Meta:\n app_label = 'repro'\n\n\nwith connection.cursor() as cursor:\n cursor.execute('CREATE EXTENSION IF NOT EXISTS vector')\n cursor.execute('DROP TABLE IF EXISTS repro_item')\nwith connection.schema_editor() as editor:\n editor.create_model(Item)\n\n\nclass ItemForm(forms.ModelForm):\n class Meta:\n model = Item\n fields = ['embedding']\n\n\nclass ItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = Item\n fields = ['embedding']\n\n\ndef check(name, fn):\n try:\n print(f'{name}: {fn()}')\n except Exception as e:\n print(f'{name}: {type(e).__name__}: {e}')\n\n\ndef form(value):\n f = ItemForm(data={'embedding': value})\n if not f.is_valid():\n return f'invalid {f.errors.get_json_data()}'\n f.save()\n return 'saved'\n\n\ndef serializer(value):\n s = ItemSerializer(data={'embedding': value})\n if not s.is_valid():\n return f'invalid {s.errors}'\n s.save()\n return 'saved'\n\n\ncheck('form [1,2,x]', lambda: form('[1,2,x]'))\ncheck('form [1,2]', lambda: form('[1,2]'))\ncheck('serializer [1, 2, \"x\"]', lambda: serializer([1, 2, 'x']))\ncheck('serializer [1, 2]', lambda: serializer([1, 2]))\n```\n\nOutput:\n\n```text\nform [1,2,x]: ValueError: could not convert string to float: 'x'\nform [1,2]: DataError: expected 3 dimensions, not 2\nserializer [1, 2, \"x\"]: ValueError: could not convert string to float: 'x'\nserializer [1, 2]: DataError: expected 3 dimensions, not 2\n```\n\nTraceback for the first case:\n\n```text\n .../django/forms/models.py\", line 503, in _post_clean\n .../django/db/models/base.py\", line 1713, in full_clean\n .../django/db/models/base.py\", line 1768, in clean_fields\n .../django/db/models/fields/__init__.py\", line 875, in clean\n .../pgvector/django/vector.py\", line 33, in to_python\n .../pgvector/vector.py\", line 112, in _from_db\n .../pgvector/vector.py\", line 88, in _from_text\nValueError: could not convert string to float: 'x'\n```\n\n### Expected\n\nAll four cases come back as invalid with a field error, and nothing reaches the database. For the dimension mismatch, the field already knows `dimensions`, so it could check the length before saving.\n\n### Versions\n\n- pgvector-python 0.5.1 (also on `master`, e0f3ac3)\n- Django 6.1.2, Django REST framework 3.18.3, Psycopg 3.3.6\n- Postgres 18.6, pgvector 0.8.7\n- Python 3.12.7\n","author":{"url":"https://github.com/ontdepart","@type":"Person","name":"ontdepart"},"datePublished":"2026-10-24T14:44:48Z","url":"https://github.com/pgvector/pgvector-python/issues/171"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:9c8ffab7-5185-5cf3-116e-a625cdf475e4 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8074:3CE0F6:9E063C:CF7942:6AFE81E9 |
| html-safe-nonce | 630c09fc096a6b51a83cd680981b9cd01b7be90e13552be184abe648bc8dad09 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MDc0OjNDRTBGNjo5RTA2M0M6Q0Y3OTQyOjZBRkU4MUU5IiwidmlzaXRvcl9pZCI6IjY2MTE1MzQ2ODE0MzMwODAyOTgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 206dbefa1cc6372d9a676e318e4371787f5ab437062c028fc4010c285527affb |
| hovercard-subject-tag | issue:6014134906 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/pgvector/pgvector-python/171/issue_layout |
| twitter:image | https://opengraph.githubassets.com/e30cdc664de74f12ab73f802180c00df3e584397a33b1679571e6484c58ff062/pgvector/pgvector-python/issues/171 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/e30cdc664de74f12ab73f802180c00df3e584397a33b1679571e6484c58ff062/pgvector/pgvector-python/issues/171 |
| og:image:alt | Hi @ankane, thanks for pgvector-python! When a VectorField gets malformed input through a ModelForm (including the admin) or a DRF ModelSerializer, the error isn't a validation error. With a non-nu... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | ontdepart |
| hostname | github.com |
| expected-hostname | github.com |
| None | b3c0f155eafc27e60db6e254d1ffff0e072e9ab3b4018a5ee518797c19d89f86 |
| turbo-cache-control | no-preview |
| go-import | github.com/pgvector/pgvector-python git https://github.com/pgvector/pgvector-python.git |
| octolytics-dimension-user_id | 98363230 |
| octolytics-dimension-user_login | pgvector |
| octolytics-dimension-repository_id | 376300726 |
| octolytics-dimension-repository_nwo | pgvector/pgvector-python |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 376300726 |
| octolytics-dimension-repository_network_root_nwo | pgvector/pgvector-python |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 4a10310af51a1bfffbedc4fd81cb582acf0cb0ff |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width