I am displaying a series of boxes in a grid, with a background color set by a value in a table called objectives… There is a Color table that has a hex color that corresponds to the value. I use that since changing the color there will change it globally in the program. I use a column sled value instead of just id to make it easier to change a reference to the color and not have to track deletion of rows.
Once the values are calculated, I lookup and update the color in Objectives with the corresponding color in Color.
I have two questions;
- While this works, it seems excessive. Is there a better way to update the colors based on changed values than:
objective_num=Objectives.objects.filter(dashboard=dashboard_id).values('id','objective_color')#get dic of latest color values for each id
for n in objective_num: #Iterate over all the objectives, starting at 0 to valeu of objective_num
color_hex = n.get('objective_color') #get color code to use to get coressponding hex value from Color table
obj_id=n.get('id') #get objective id for the color
color = Color.objects.filter(value=color_hex).values_list('objective_background', flat=True) #get color hex value that natches teh color set in Objectives
Objectives.objects.filter(dashboard=dashboard_id).filter(id=obj_id).update(objective_background=color) #update color hex in Objectives table
- While it is intended only to use current values, someone will want historical ones at some point. I was thinking about creating a historical table, where I add a column every update, a very Excel way of doing it. Alternatively, I could add rows with each update and number them to be able to get historical data. That way, I need only save the change values. Any suggestions as to which approach is better?
Models
class Color(models.Model):
color=models.CharField(max_length=10, default = 'White')
objective_background = models.CharField(max_length=7, default='#FFFFFF')
value=models.IntegerField( default = 1)
def __str__(self):
return f"{self.color} (Hex: {self.objective_background }) is color number {self.value} with ID {self.id}"
class Objectives(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
dashboard=models.ForeignKey(Dashboard, on_delete=models.CASCADE)
objective_background = models.CharField(max_length=8, default=1)
row = models.ForeignKey(Row, on_delete=models.CASCADE)
objective_position = models.IntegerField()
objective_color = models.IntegerField() #Used to store status color based on performance
objective_text = models.CharField(max_length=1000, blank = True)
timestamp= models.TimeField(auto_now = True)
def __str__(self):
return f" Objective: {self.row} {self.objective_position} {self.objective_text} at {self.timestamp}"