如何使用Django管理外连接,group_by和count

时间:2016-03-25 17:32:33

标签: sql django django-models django-queryset

使用Django我有以下模型:

class Player(models.Model):
    name = models.CharField(max_length=64)
    description = models.CharField(max_length=128)
    groupPlayer = models.ForeignKey(GroupPlayer)


class GroupPlayer(models.Model):
    description = models.CharField(max_length=128)
    name = models.CharField(max_length=32)

每个玩家都与一个群组相关联。有些人没有球员。我的目的是翻译Django中的跟随查询(包括LEFT OUTER JOIN和Group by):

select GroupPlayer.description, GroupPlayer.name, COUNT(Player.name) as gplayer
from (GroupPlayer LEFT OUTER JOIN Player ON GroupPlayer.id = Player.groupPlayer_id)
GROUP BY GroupPlayer.id

到目前为止,我已创建了3个查询集,但我无法将它们放在一起以获得我希望的结果:

   queryset_player = Player.objects.values('groupPlayer_id').annotate(total=Count('groupPlayer__id'))
   queryset_group = GroupPlayer.objects.select_retated(queryset_player)
   queryset_group2 = GroupPlayer.objects.all().prefetch_related('player_set')

任何人都可以帮助进行LEFT OUTER JOIN,分组和计数?

由于

1 个答案:

答案 0 :(得分:0)

pages=`git rev-parse gh-pages`
git update-ref refs/heads/gh-pages $(
        git commit-tree ${pages:+-p gh-pages} -m "built pages" master:build
)

Aggragation