2011-06-15 49 views
0

我有以下型號的COUNT -添加一列外鍵對象

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') 
    ... 

我想補充的計數的視頻用戶擁有的數量。

目前,要得到一個用戶的數量,我可以做profile.video_set.count()

我想在UserProfile模型中增加一列,這樣我就可以做UserProfile.objects.order_by('video_count')。我如何將這個自定義行添加到模型?謝謝。

回答

2

您正在嘗試執行的操作不遵循database normalization規則。去的方法是使用一個註釋:

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

如果你寧願你的非規範化計數器,性能,或任何其他原因,django-counter-field讓你輕鬆做到這一點:

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)