Wednesday, 15 July 2015

Django: aggregating field values from different models -



Django: aggregating field values from different models -

if models structured this:

class hour(models.model): stat1 = models.floatfield() stat2 = models.floatfield() stat3 = models.floatfield() class day(models): hr = models.foreignkey(hour) #e.g.: hour.id=1, hour.id=2, ..., hour.id=24 class weather(models.model): day = models.foreignkey(day)

note: hours might missing days , stats might missing hours. collection of info lacks hours every day , stats every hour.

what best method summing , averaging stats on hierarchy of models? example, lets wanted sum , average of stat2 @ h5 days weather has info when know of days don't have info h5?

update: own solution, assumes day.id equal hr of day: e.g. if day.id == 5, it's h5 of day:

hours = [[hour hr in w.day.objects.all() if hour.id==5] \ w in weather.objects.all()] var2_sum = [sum(h.var2 h in hours if hasattr(h,'var2'))] var2_count = [count(h.var2 h in hours if hasattr(h,'var2'))] var2_avg = var2_sum / var2_count

update: own solution, assumes day.id equal hr of day: e.g. if day.id == 5, it's h5 of day:

hours = [[hour hr in w.day.objects.all() if hour.id==5] \ w in weather.objects.all()] var2_sum = [sum(h.var2 h in hours if hasattr(h,'var2'))] var2_count = [count(h.var2 h in hours if hasattr(h,'var2'))] var2_avg = var2_sum / var2_count

nested forloops fun , all, brute forcefulness way reply question. utilize of hasattr necessary avoid have none entries lists created list comprehension.

django django-models

No comments:

Post a Comment