Hello everyone, please tell me how to correctly select statistics from the table, there are the following models:

def get_hour_ts(): return int(time.time()/3600) class MainObject(models.Model): dt_created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) def __unicode__(self): return self.name class Stats(models.Model): main_obj = models.ForeignKey(MainObject, related_name='statistic', on_delete=models.CASCADE) shows = models.IntegerField(default=0) requested = models.IntegerField(default=0) dt_hour = models.IntegerField(default=get_hour_ts) def __unicode__(self): return str(self.dt_hour) class Meta: unique_together = (("main_obj", "dt_hour"),) 

Further I create serializers:

 class StatsSerializer(serializers.ModelSerializer): total_shows = serializers.IntegerField() total_requested = serializers.IntegerField() class Meta: model = Stats fields = ['total_shows', 'total_requested'] class MainObjectSerializer(serializers.ModelSerializer): statistic = StatsSerializer() name = serializers.CharField() dt_created = serializers.DateTimeField(read_only=True) class Meta: model = MainObject 

and in the end I wanted to get the data on the aggregated statistics correctly, and use a minimum of queries to the database, i.e. It is possible to use prefetch_related ('statistic'). well, to get the main object from one view at once, along with the associated statistics .. so far implemented through the serializer and the field method as follows:

 class MainObjectSerializer(serializers.ModelSerializer): def get_stats(self, obj): stats_query = Stats.objects.filter(main_obj=obj.pk).aggregate(total_shows=Sum('shows'), total_requested=Sum('requested')) data = StatsSerializer(stats_query).data return data statistic = serializers.SerializerMethodField('get_stats') 

The truth is that this approach does not quite suit me, because For each object, a request for statistics is executed. Tell me, please, how to do it correctly.

    0