Consider the following JSON structure:
{
"timesheets": [
{
"user": {
"username": "erik",
"first_name": "Erik",
},
"project_id": 4,
"calc_full_week": {
"2020-06-22": 5,
"2020-06-23": 10,
"2020-06-24": 8,
"2020-06-25": 13,
"2020-06-26": null,
"2020-06-27": null,
"2020-06-28": null
}
},
{
"user": {
"username": "erik",
"first_name": "Erik",
},
"project_id": 4,
"calc_full_week": {
"2020-06-29": 15,
"2020-06-30": 10,
"2020-07-01": null,
"2020-07-02": null,
"2020-07-03": null,
"2020-07-04": null,
"2020-07-05": null
}
},
{
"user": {
"username": "rawwe",
"first_name": "joey",
},
"project_id": 4,
"calc_full_week": {
"2020-06-22": 3,
"2020-06-23": 10.4,
"2020-06-24": 8,
"2020-06-25": 8,
"2020-06-26": 8,
"2020-06-27": 8,
"2020-06-28": 5
}
}
]
}
I am seeking an efficient way to extract the sum of values from calc_full_week
within a specified range. For example, if I provide the range 2020-06-25 - 2020-07-03
, the total sum of values within that range should be calculated (13+15+10+8+8+8+5 for the given JSON).
Now, the dilemma is whether to perform these calculations on the backend (django) or using JavaScript on the client side.
In my Django model, the structure is as shown below:
class Timesheet(Model):
year = PositiveIntegerField(validators=[MaxValueValidator(2500), MinValueValidator(1900)])
week = PositiveIntegerField()
project = ForeignKey("projects.Project", on_delete=CASCADE)
user = ForeignKey("accounts.User", on_delete=CASCADE)
day_1 = DecimalField("monday", blank=True, null=True, max_digits=4, decimal_places=1)
day_2 = DecimalField("tuesday", blank=True, null=True, max_digits=4, decimal_places=1)
day_3 = DecimalField("wednesday", blank=True, null=True, max_digits=4, decimal_places=1)
day_4 = DecimalField("thursday", blank=True, null=True, max_digits=4, decimal_places=1)
day_5 = DecimalField("friday", blank=True, null=True, max_digits=4, decimal_places=1)
day_6 = DecimalField("saturday", blank=True, null=True, max_digits=4, decimal_places=1)
day_7 = DecimalField("sunday", blank=True, null=True, max_digits=4, decimal_places=1)
I serialize this data and include a
calc_full_week = serializers.SerializerMethodField()
attribute, with the calculation logic detailed in the method below:
def get_calc_full_week(self, obj):
current_week = obj.week
current_year = obj.year
# Since week 1 corresponds to week 0
week = current_week - 1
# List containing each date of a given week
startdate = time.asctime(time.strptime('%d %d 1' % (current_year, week), '%Y %W %w'))
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y')
date_dict = {}
days_in_week = [obj.day_1, obj.day_2, obj.day_3, obj.day_4, obj.day_5, obj.day_6, obj.day_7]
for i in range(0, 7):
day = startdate + datetime.timedelta(days=i)
date_dict[day.strftime('%Y-%m-%d')] = days_in_week[i]
return date_dict