Django queryset - column IN() GROUP BY HAVING COUNT DISTINCT

天大地大妈咪最大 提交于 2021-01-28 17:55:51

问题


With the following models:

class Post(models.Model):

    class Meta:
        db_table = "posts"

class Tag(models.Model):
    tag = models.CharField(max_length=50)

   class Meta:
       db_table = "tags"

class PostTag(models.Model):
    postid = models.PositiveIntegerField()
    tagid = models.PositiveIntegerField()

    class Meta:
        unique_together = ("postid", "tagid")
        db_table = "posttags"

To get postids of posts which contain all the tagids given in TAGLIST where TAGLEN is the number of tagids in TAGLIST:

SELECT postid
FROM posttags
WHERE tagid IN (TAGLIST)
GROUP BY postid
HAVING COUNT(DISTINCT tagid) = TAGLEN

But how do I do this with Django ORM?


回答1:


I found a solution.

    TAGLEN = TAGLIST.count()
    withtags = PostTag.objects.filter(tagid__in=TAGLIST)
    withall = withtags.values("postid").annotate(tagtotal=Count("tagid", distinct=True)).order_by()
    withall.filter(tagtotal=TAGLEN).values_list("postid", flat=True)

And running .query.__str__() on all this returns basically the following SQL below.

SELECT "postid"
FROM "posttags"
WHERE "tagid" IN (TAGLIST)
GROUP BY "postid"
HAVING COUNT(DISTINCT "tagid") = TAGLEN'


来源:https://stackoverflow.com/questions/47304612/django-queryset-column-in-group-by-having-count-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!