extensions-website/extensions/fields.py

37 lines
1.0 KiB
Python

from django.core.exceptions import ValidationError
from semantic_version.django_fields import VersionField as SemanticVersionField
from semantic_version import Version
import json
class VersionStringField(SemanticVersionField):
description = "A field to store serializable semantic versions"
def to_python(self, value):
if isinstance(value, Version):
return value
if value is None:
return value
try:
return str(Version(value))
except Exception as e:
raise ValidationError(e)
def from_db_value(self, value, expression, connection):
return self.to_python(value)
def get_prep_value(self, value):
if value is None:
return value
return str(value)
def value_to_string(self, obj):
value = self.value_from_object(obj)
return self.get_prep_value(value)
def from_json(self, json_str):
return self.to_python(json.loads(json_str))
def to_json(self, value):
return json.dumps(str(value))