django-postgres-commaseparatedarrayfield 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,224 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-postgres-commaseparatedarrayfield
3
+ Version: 1.0.0
4
+ Summary: Django model field for PostgreSQL ArrayField that can import comma-separated values
5
+ Keywords: arrayfield,comma-separated,django,postgres,postgresql
6
+ Author: blag
7
+ Author-email: blag <blag@users.noreply.github.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: Django :: 5.2
13
+ Classifier: Framework :: Django :: 6.0
14
+ Classifier: Framework :: Django :: 6.1
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Requires-Dist: django>=5.2
22
+ Requires-Dist: psycopg[binary]>=3.1
23
+ Requires-Python: >=3.12
24
+ Project-URL: Homepage, https://github.com/blag/django-postgres-commaseparatedarrayfield
25
+ Project-URL: Repository, https://github.com/blag/django-postgres-commaseparatedarrayfield
26
+ Project-URL: Issues, https://github.com/blag/django-postgres-commaseparatedarrayfield/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ # django-postgres-commaseparatedarrayfield
30
+
31
+ A Django model field for PostgreSQL `ArrayField` that accepts and parses comma-separated string input.
32
+
33
+ Django's built-in `ArrayField` expects a Python list (or JSON-encoded string) — it has no way to accept the "a, b, c"
34
+ format that comes from CSV imports, Excel cells, or user pastes. `CommaSeparatedArrayField` fills that gap by
35
+ overriding `to_python()` to split on commas, strip whitespace, and discard empty segments.
36
+
37
+ ## Features
38
+
39
+ - **Drop-in replacement** for `django.contrib.postgres.fields.ArrayField`.
40
+ - **Comma-separated parsing**: accepts `"Paris, Paris9, Paris XI"` as input and stores
41
+ `["Paris", "Paris9", "Paris XI"]`.
42
+ - **Quoted values**: items containing commas can be wrapped in double quotes — `paris,"Paris, XI",Paris9` →
43
+ `["paris", "Paris, XI", "Paris9"]`.
44
+ - **Form-aware**: ships a `CommaSeparatedArrayFormField` that round-trips values correctly through Django forms and the
45
+ admin, quoting any item that contains the delimiter.
46
+ - **Smart input handling**: lists, tuples, and `None` pass through unchanged; only strings are split.
47
+ - **Safe default**: injects `default=list` automatically so new model instances start with an empty array.
48
+ - **Fully tested** with pytest + pytest-django (100% branch coverage).
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ pip install django-postgres-commaseparatedarrayfield
54
+ ```
55
+
56
+ ```bash
57
+ poetry add django-postgres-commaseparatedarrayfield
58
+ ```
59
+
60
+ ```bash
61
+ uv add django-postgres-commaseparatedarrayfield
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ### Model definition
67
+
68
+ ```python
69
+ from django.db import models
70
+ from pg_commaseparatedarrayfield import CommaSeparatedArrayField
71
+
72
+ class GeoName(models.Model):
73
+ name = models.CharField(max_length=200)
74
+ alternatenames = CommaSeparatedArrayField(models.CharField())
75
+ ```
76
+
77
+ No `default=` is required -- the field defaults to an empty list (`[]`) automatically -- but it can still be specified
78
+ if you need:
79
+
80
+ ```python
81
+ from django.db import models
82
+ from pg_commaseparatedarrayfield import CommaSeparatedArrayField
83
+
84
+ def alternatenames_default():
85
+ return ["Lutece"]
86
+
87
+ class GeoName(models.Model):
88
+ name = models.CharField(max_length=200)
89
+ alternatenames = CommaSeparatedArrayField(models.CharField(), default=alternatenames_default)
90
+ ```
91
+
92
+ ### Saving with a comma-separated string
93
+
94
+ ```python
95
+ from examples.models import GeoName
96
+
97
+ obj = GeoName(
98
+ name="Paris",
99
+ alternatenames="Paris, Paris9, Paris XI",
100
+ )
101
+ obj.save()
102
+
103
+ # The field is parsed on assignment/initialization:
104
+ print(obj.alternatenames) # ["Paris", "Paris9", "Paris XI"]
105
+ ```
106
+
107
+ ### Saving with a list (still works)
108
+
109
+ ```python
110
+ obj = GeoName(
111
+ name="London",
112
+ alternatenames=["London", "Lundin"],
113
+ )
114
+ obj.save()
115
+ ```
116
+
117
+ ### Values containing commas
118
+
119
+ If an individual value contains a comma, wrap it in double quotes (standard CSV convention):
120
+
121
+ ```python
122
+ obj = GeoName(
123
+ name="Paris",
124
+ alternatenames='Paris,"Paris, XI",Paris9',
125
+ )
126
+ obj.save()
127
+
128
+ print(obj.alternatenames) # ["Paris", "Paris, XI", "Paris9"]
129
+ ```
130
+
131
+ In Django forms and the admin, values with embedded commas are automatically quoted on display and parsed with the same
132
+ convention on submit:
133
+
134
+ ```
135
+ HTML input value: Paris,"Paris, XI",Paris9
136
+ ```
137
+
138
+ ### Loading from the database
139
+
140
+ Values are returned as lists, just like the standard `ArrayField`:
141
+
142
+ ```python
143
+ obj = GeoName.objects.get(name="Paris")
144
+ print(obj.alternatenames) # ["Paris", "Paris, XI", "Paris9"]
145
+ ```
146
+
147
+ ### NULL handling
148
+
149
+ ```python
150
+ obj = GeoName(name="Test", alternatenames=None)
151
+ obj.save() # stored as NULL, not an empty array
152
+ ```
153
+
154
+ ## How it works
155
+
156
+ ### Model field — `to_python()`
157
+
158
+ `CommaSeparatedArrayField` extends `ArrayField` and overrides `to_python()` using Python's `csv` module for parsing:
159
+
160
+ | Input | Behavior |
161
+ | ----- | ------- |
162
+ | `None` | Returns `None` (field is NULL) |
163
+ | `list` / `tuple` | Passed through to `ArrayField.to_python()` unchanged |
164
+ | `str` | Parsed with `csv.reader`, each item stripped of surrounding whitespace, empty items discarded |
165
+ | Any other type | Passed through to `ArrayField.to_python()` |
166
+
167
+ The `csv`-based parser understands standard CSV quoting: an item wrapped in double quotes may contain the delimiter
168
+ (comma) without being split.
169
+
170
+ ### Form field — `CommaSeparatedArrayFormField`
171
+
172
+ `CommaSeparatedArrayField.formfield()` returns a `CommaSeparatedArrayFormField` (a subclass of Django's
173
+ `SimpleArrayField`). This ensures the form and admin use the same csv-aware parsing, and that values containing commas
174
+ are double-quoted when rendered into the HTML input for unambiguous round-tripping.
175
+
176
+ You can also use the form field directly in a `ModelForm` if you need to customize the delimiter:
177
+
178
+ ```python
179
+ from django import forms
180
+ from pg_commaseparatedarrayfield import CommaSeparatedArrayFormField
181
+
182
+ class GeoNameForm(forms.ModelForm):
183
+ class Meta:
184
+ model = GeoName
185
+ fields = ["name", "alternatenames"]
186
+
187
+ alternatenames = CommaSeparatedArrayFormField(
188
+ base_field=forms.CharField(max_length=200),
189
+ delimiter=", ",
190
+ )
191
+ ```
192
+
193
+ ## Requirements
194
+
195
+ - Python 3.12+
196
+ - Django 5.2, 6.0, or 6.1
197
+ - PostgreSQL (via `psycopg[binary]`)
198
+
199
+ ## Development
200
+
201
+ ```bash
202
+ # Install dependencies (creates .venv)
203
+ uv sync
204
+
205
+ # Run tests
206
+ uv run pytest
207
+
208
+ # Run with example app
209
+ uv run python manage.py runserver
210
+ ```
211
+
212
+ Tests that require a live PostgreSQL database are skipped automatically. To run the full suite including DB integration
213
+ tests, set the environment variables:
214
+
215
+ ```bash
216
+ export DB_DATABASE=mydb
217
+ export DB_USERNAME=myuser
218
+ export DB_PASSWORD=mypass
219
+ uv run pytest
220
+ ```
221
+
222
+ ## License
223
+
224
+ MIT
@@ -0,0 +1,7 @@
1
+ pg_commaseparatedarrayfield/__init__.py,sha256=1BXy2NpxwiKSrcFAovs-56iUTObz3zwl60FenhU547U,280
2
+ pg_commaseparatedarrayfield/apps.py,sha256=SVVNnyZntWRywAJG5P4O7eSwGs9n3FFhUU85oqS6s4o,306
3
+ pg_commaseparatedarrayfield/fields.py,sha256=oG2JetoG26jhcUqwiNS6-zAViZasw7p99wWIeyuOMaA,4603
4
+ django_postgres_commaseparatedarrayfield-1.0.0.dist-info/licenses/LICENSE,sha256=B2u0rcvlCAt1EPDwI-OBxiK36zkV9Wx3R8fU6MvJbPM,1061
5
+ django_postgres_commaseparatedarrayfield-1.0.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
6
+ django_postgres_commaseparatedarrayfield-1.0.0.dist-info/METADATA,sha256=RypNEI1q119ytC79SRp-Ux9fg9LitRVeELDV-tzFwAE,6784
7
+ django_postgres_commaseparatedarrayfield-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.12
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 blag
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,9 @@
1
+ from importlib import metadata
2
+
3
+ from .fields import *
4
+
5
+ # Fall back for development checkouts where the package isn't installed yet.
6
+ try:
7
+ __version__ = metadata.version("django-postgres-commaseparatedarrayfield")
8
+ except metadata.PackageNotFoundError:
9
+ __version__ = "0.0.0"
@@ -0,0 +1,8 @@
1
+ from django.apps import AppConfig
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+
5
+ class PostgresCommaSeparatedArrayFieldConfig(AppConfig):
6
+ default_auto_field = "django.db.models.BigAutoField"
7
+ name = "pg_commaseparatedarrayfield"
8
+ verbose_name = _("PostgreSQL CommaSeparatedArrayField")
@@ -0,0 +1,128 @@
1
+ import csv
2
+ import io
3
+
4
+ from django.contrib.postgres.fields import ArrayField
5
+ from django.contrib.postgres.forms import SimpleArrayField
6
+ from django.core.exceptions import ValidationError
7
+ from django.contrib.postgres.utils import prefix_validation_error
8
+
9
+
10
+ __all__ = ["CommaSeparatedArrayField", "CommaSeparatedArrayFormField"]
11
+
12
+
13
+ def _parse_comma_separated(value):
14
+ """Parse a comma-separated string, respecting double-quoted fields.
15
+
16
+ Uses the standard CSV convention: an item may contain commas if it is
17
+ wrapped in double quotes, e.g. ``paris,"quoted, with commas",tokyo``.
18
+ Each item is stripped of surrounding whitespace; empty items are removed.
19
+ """
20
+ reader = csv.reader(io.StringIO(value))
21
+ try:
22
+ row = next(reader)
23
+ except StopIteration:
24
+ return []
25
+ return [sitem for item in row if (sitem := item.strip())]
26
+
27
+
28
+ class CommaSeparatedArrayField(ArrayField):
29
+ def __init__(self, base_field, *args, **kwargs):
30
+ # Ensure default is a callable to avoid mutable default argument issues
31
+ if "default" not in kwargs:
32
+ kwargs["default"] = list
33
+ super().__init__(base_field, *args, **kwargs)
34
+
35
+ def to_python(self, value):
36
+ if value is None:
37
+ return None
38
+
39
+ # If it's already a list/tuple (e.g., from database or manual assignment),
40
+ # let ArrayField handle standard validation
41
+ if isinstance(value, (list, tuple)):
42
+ return super().to_python(value)
43
+
44
+ # Handle comma-separated strings (csv-aware for quoted fields)
45
+ if isinstance(value, str):
46
+ return super().to_python(_parse_comma_separated(value))
47
+
48
+ # Fallback for other types
49
+ return super().to_python(value)
50
+
51
+ def pre_save(self, model_instance, add):
52
+ """Normalize the attribute to a list before it enters the save path.
53
+
54
+ Django's SQL compiler calls pre_save() to get the field value from
55
+ the model instance. If the user set a raw string (e.g.
56
+ ``obj.alternatenames = "a, b, c"``), we parse it into a list here
57
+ and write it back to the instance so the in-memory state matches
58
+ what will be persisted.
59
+ """
60
+ value = getattr(model_instance, self.attname)
61
+ if isinstance(value, str):
62
+ value = _parse_comma_separated(value)
63
+ setattr(model_instance, self.attname, value)
64
+ return value
65
+
66
+ def get_db_prep_save(self, value, connection):
67
+ """Parse comma-separated strings before they reach PostgreSQL.
68
+
69
+ Defense-in-depth: if a string somehow slips through pre_save (e.g.
70
+ a raw SQL save or a code path that bypasses pre_save), parse it
71
+ here before ArrayField.get_db_prep_save() would pass it to
72
+ PostgreSQL as-is.
73
+ """
74
+ if isinstance(value, str):
75
+ value = _parse_comma_separated(value)
76
+ return super().get_db_prep_save(value, connection)
77
+
78
+ def formfield(self, **kwargs):
79
+ kwargs.setdefault("form_class", CommaSeparatedArrayFormField)
80
+ return super().formfield(**kwargs)
81
+
82
+
83
+ class CommaSeparatedArrayFormField(SimpleArrayField):
84
+ """Form field that parses comma-separated values with csv-aware logic.
85
+
86
+ On display, items containing the delimiter are double-quoted so the
87
+ value round-trips correctly through the form.
88
+ """
89
+
90
+ def to_python(self, value):
91
+ if isinstance(value, list):
92
+ items = value
93
+ elif value:
94
+ items = _parse_comma_separated(value)
95
+ else:
96
+ items = []
97
+
98
+ errors = []
99
+ values = []
100
+ for index, item in enumerate(items):
101
+ try:
102
+ values.append(self.base_field.to_python(item))
103
+ except ValidationError as error:
104
+ errors.append(
105
+ prefix_validation_error(
106
+ error,
107
+ prefix=self.error_messages["item_invalid"],
108
+ code="item_invalid",
109
+ params={"nth": index + 1},
110
+ )
111
+ )
112
+ if errors:
113
+ raise ValidationError(errors)
114
+ return values
115
+
116
+ def prepare_value(self, value):
117
+ if isinstance(value, list):
118
+ return self.delimiter.join(
119
+ self._prepare_item(str(self.base_field.prepare_value(v)))
120
+ for v in value
121
+ )
122
+ return value
123
+
124
+ def _prepare_item(self, s):
125
+ """Quote items that contain the delimiter for unambiguous round-tripping."""
126
+ if self.delimiter in s:
127
+ return '"{}"'.format(s.replace('"', '""'))
128
+ return s