I have the following models —
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
...
class Video(models.Model):
title = models.CharField(max_length=256)
uploaded_by = models.ForeignKey('UserProfile')
...
I would like to add a COUNT for the number of videos a user has.
Currently, to get the count of a user, I can do profile.video_set.count().
I would like to have an additional column in the UserProfile model so I can just do UserProfile.objects.order_by('video_count'). How would I add this custom row to the model? Thank you.
What you are trying to do does not follow database normalization rules. The way to go is by using an annotation: