Skip to content

Commit

Permalink
Fixes up models to swap out on db type
Browse files Browse the repository at this point in the history
This is a bit of a hack but it's the only way to truly dynamically swap
between models. We use a custom array field in sqllite and use standard
array field in postgres.

This also removes some faulty migrations
  • Loading branch information
elijahbenizzy committed Jun 10, 2024
1 parent 49712d0 commit 02b058a
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 94 deletions.
31 changes: 7 additions & 24 deletions ui/backend/server/trackingserver_base/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json

from django.conf import settings
from django.contrib.postgres.fields import ArrayField as BaseArrayField
from django.db import models

Expand Down Expand Up @@ -56,14 +57,6 @@ class Meta:
abstract = True


def _is_postgres():
from django.conf import settings

out = settings.DB == "django.db.backends.postgresql"
assert out
return out


class ArrayField(models.Field):
"""
A field that acts like an ArrayField when using PostgreSQL and as a serialized TextField when using SQLite.
Expand All @@ -79,39 +72,29 @@ def deconstruct(self):
return name, path, (self.base_field,) + tuple(args), kwargs

def db_type(self, connection):
if _is_postgres():
return self.array_field.db_type(connection)
else:
return "text"
return "text"

def from_db_value(self, value, expression, connection):
if _is_postgres():
return value
if value is None:
return value
return json.loads(value)

def to_python(self, value):
if _is_postgres():
return self.array_field.to_python(value)
if isinstance(value, list) or value is None:
return value
return json.loads(value)

def get_prep_value(self, value):
if _is_postgres():
return self.array_field.get_prep_value(value)
def get_db_prep_save(self, value, connection):
return json.dumps(value)

def get_db_prep_save(self, value, connection):
if _is_postgres():
return self.array_field.get_db_prep_save(value, connection)
def get_prep_value(self, value):
return json.dumps(value)

def value_to_string(self, obj):
if _is_postgres():
return self.array_field.value_to_string(obj)
value = self.value_from_object(obj)
if isinstance(value, list):
return json.dumps(value)
return value


ArrayField = ArrayField if settings.DB == "django.db.backends.sqlite3" else BaseArrayField

This file was deleted.

This file was deleted.

0 comments on commit 02b058a

Please sign in to comment.