0

I have the following two QuerySets

movies_actor=[<Movie: DJango>, <Movie: Paloma de papel>, <Movie: Asu Mare: la película>, <Movie: Mariposa negra>, <Movie: Mañana te cuento>, <Movie: No se lo digas a nadie>]

movies_genres=[<Movie: Dias de Santiago>, <Movie: Ciudad M>, <Movie: DJango>, <Movie: Mariposa negra>, <Movie: No se lo digas a nadie>, <Movie: La Gran Sangre: La Pelicula>, <Movie: La Ciudad y Los Perros>, <Movie: Paloma de papel>]

Each element of the two query sets has the attribute counter. For example movie_actor[0].counter=2. I need to merge and sum this atributte in another QuerySet. Could you help me to obtain that please?

Juan
  • 2,073
  • 3
  • 22
  • 37

2 Answers2

0

Following this answer you could first merge your querysets:

    merged_queryset = movies_actor | movies_genres

and then do the aggregation:

    total = merged_queryset.agggregate(Sum('counter'))

I have tried it with similar models on Django 1.8 and it works perfectly.

Community
  • 1
  • 1
Marco A.
  • 535
  • 2
  • 10
-1

you can use Aggregation:

sum_movies_actor = movies_actor.aggregate(Sum('counter'))
sum_movies = movies.aggregate(Sum('counter'))
total = sum_movies_actor['counter__sum'] + sum_movies['counter__sum']
Tim
  • 1,272
  • 11
  • 28