如何在django中创建原始sql ManyToMany和Annotation?

时间:2015-12-08 12:11:45

标签: sql django annotate

class Post(models.Model):
    user = models.ForeignKey(FBUser, related_name='posts')
    group = models.ForeignKey(Group, related_name='posts')

class Comment(models.Model):
    user = models.ForeignKey(FBUser, related_name='comments')
    post = models.ForeignKey(Post, related_name='comments')
    group = models.ForeignKey(Group, related_name='comments')

class Group(models.Model):
    name = models.CharField(max_length=100)

我制作了这段代码,但是这段代码在10秒内获得结果的速度非常慢。

_group.user_set.filter(posts__group=_group, comments__group=_group) \
            .annotate(p_count=Count('posts', distinct=True), c_count=Count('comments', distinct=True))

如何将此代码转换为原始sql?

0 个答案:

没有答案