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的方式這樣做?
試試這個:'想= Games.objects.filter(國有= 0).annotate(vote_count =計數( '票')))ORDER_BY(' - vote_count。 ')'(未測試) – karthikr
@karthikr工作感謝! – hanleyhansen