Given a JSON that looks like this:
{
"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
}
}
]
}
How can I efficiently extract the sum of the values in calc_full_week
for a given range? E.g, if I provide the range 2020-06-25 - 2020-07-03
I want to to get the sum of all values that fit that range. (13+15+10+8+8+8+5 for the JSON provided)
Not sure if I should do the calculations on the backend (django) or with javascript on the client side.
My model in django looks like this:
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'm serializing this and adding a calc_full_week = serializers.SerializerMethodField()
value, where the SerializedMethodField looks like this:
def get_calc_full_week(self, obj):
current_week = obj.week
current_year = obj.year
# since week 1 is actually week 0
week = current_week - 1
# list with 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