models.py 1.72 KB
from django.db import models
from django.db.models import JSONField, DateField
import numpy as np
# Create your models here.


import json
from json import JSONEncoder
import numpy

class NumpyArrayEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, numpy.ndarray):
            return obj.tolist()
        return JSONEncoder.default(self, obj)
    


class EffectiveSchedule(models.Model):
    scheduler_matrix = JSONField(blank=True, null=True)    

    def save(self, *args, **kwargs):
        # Transform numpy matrix to JSON
        scheduler_matrix_as_json = json.dumps(self.scheduler_matrix, cls=NumpyArrayEncoder)
        self.scheduler_matrix = scheduler_matrix_as_json
        super(EffectiveSchedule, self).save(*args, **kwargs)

    def get(self, *args, **kwargs):
        # Transform JSON to numpy matrix 
        matrix_as_json = json.loads(self.scheduler_matrix)

        self.scheduler_matrix = numpy.asarray(matrix_as_json["array"]) 
        return super().get(**kwargs)
    
class PredictiveSchedule(models.Model):
    scheduler_matrix = JSONField(blank=True, null=True)    

    def save(self, *args, **kwargs):
        # Transform numpy matrix to JSON
        scheduler_matrix_as_json = json.dumps(self.scheduler_matrix, cls=NumpyArrayEncoder)
        self.scheduler_matrix = scheduler_matrix_as_json
        super(EffectiveSchedule, self).save(*args, **kwargs)

    def get(self, *args, **kwargs):
        # Transform JSON to numpy matrix 
        matrix_as_json = json.loads(self.scheduler_matrix)

        self.scheduler_matrix = numpy.asarray(matrix_as_json["array"]) 
        return super().get(**kwargs)
    

class SchedulerHistory(EffectiveSchedule):
    night_date = models.DateField(blank=True, null=True)