-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathfields.py
More file actions
59 lines (52 loc) · 1.68 KB
/
fields.py
File metadata and controls
59 lines (52 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# SPDX-FileCopyrightText: (C) 2023 - 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import json
from django.db import models
from django.conf import settings
if 'postgresql' in settings.DATABASES['default']['ENGINE']:
from django.contrib.postgres.fields import ArrayField
class ListField(ArrayField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('base_field', models.FloatField())
kwargs.setdefault('default', list)
super().__init__(*args, **kwargs)
def from_db_value(self, value, expression, connection):
if value is None:
return []
return value
def get_prep_value(self, value):
if value is None:
return []
return list(value)
else:
class ListField(models.JSONField):
"""Robust JSONField for list of floats, handles double-encoded JSON."""
def from_db_value(self, value, expression, connection):
if value is None:
return []
while isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
return []
if isinstance(value, list):
return [float(v) for v in value if isinstance(v, (int, float, str))]
return []
def get_prep_value(self, value):
"""Prepare list of floats for DB storage."""
if value is None:
return []
while isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
return []
if isinstance(value, list):
result = []
for v in value:
try:
result.append(float(v))
except (ValueError, TypeError):
continue
return result
return []