开发者

Add a column for COUNT of foreign key objects

开发者 https://www.devze.com 2023-03-13 02:05 出处:网络
I have the following models -- class UserProfile(models.Model): user = models.ForeignKey(User, unique=True)

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('开发者_Python百科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:

UserProfile.objects.annotate(video_count=Count('video')).order_by('-video_count')


If you would rather denormalize your counters, for performance, or any other reason, django-counter-field lets you easily do that:

from django_counter_field import CounterField, CounterMixin, connect_counter

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    video_count = CounterField()
    ...

class Video(CounterMixin, models.Model):
    title = models.CharField(max_length=256)
    uploaded_by = models.ForeignKey('UserProfile')
    ...

connect_counter('video_count', Video.uploaded_by)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号