Q:

Django Models: Aggregate over not directly related models

I have following models:
class UserProfile(models. Model):
user = models. OneToOneField(User, on_delete=models. CASCADE, primary_key=True)
some_field = models. CharField(max_length=100)

class UserRating(models. Model):
subject_user = models. ForeignKey(User, related_name='rated_user', on_delete=models. CASCADE)
rating_user = models. ForeignKey(User, related_name='rating_user', on_delete=models. CASCADE)
rating = models. IntegerField()

    class Meta:
        unique_together = ("subject_user", "rating_user")

I am trying to get a queryset of all UserProfiles with annotated average value of rating in UserRating model. 
I've tried doing the following:
    queryset = UserProfile.objects.all()
    for profile in queryset:
        user = profile.user
        ratingset = UserRating.objects.filter(subject_user = user).values_list('rating')
        if len(ratingset) == 0:
            profile.rating = 0
        else:
        profile.rating = sum(ratingset) / float(len(ratingset))

However this throws the following error:
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

I thought about calculating the sum by iterating over ratingset, but my approach seems like an overkill.  Is there any simpler way to achieve this? 

A:

Django actually offers various methods for aggregating directly via SQL which is far more efficient.  This should get the job done:
profiles_with_ratings = UserProfile.objects.annotate(rating=Avg('user__rated_user__rating'))

docs here: https://docs.djangoproject.com/en/2.0/topics/db/aggregation/
Side note: what you actually have is a many to many relationship between users that you're building manually for some reason.