2013-12-12 46 views
0

我已經定義的模型,像這樣:Django的ORM表關係

class Games(models.Model): 
    title = models.CharField(max_length=50) 
    owned = models.BooleanField(default=False) 
    created = models.DateTimeField(auto_now_add=True) 


class Votes(models.Model): 
    game = models.ForeignKey(Games) 
    created = models.DateTimeField(auto_now_add=True) 

而且我在做我的觀點如下:

wanted = Games.objects.filter(owned=0) 
for game in wanted: 
    game.vote = Votes.objects.all().filter(game_id=game.id).count() 
wanted = sorted(wanted, key=attrgetter('vote'), reverse=True) 

它工作正常,但有一個更Django的方式這樣做?

+3

試試這個:'想= Games.objects.filter(國有= 0).annotate(vote_count =計數( '票')))ORDER_BY(' - vote_count。 ')'(未測試) – karthikr

+0

@karthikr工作感謝! – hanleyhansen

回答

1
from django.db.models import Count 
Games.objects.filter(owned=0).annotate(vote=Count('votes')).order_by('-vote') 

看到Django aggregation以獲取更多信息

+0

非常好。感謝您也收錄了文檔。確切地說,我正在尋找的答案類型。 – hanleyhansen