【问题标题】:Django queryset - column IN() GROUP BY HAVING COUNT DISTINCTDjango 查询集 - 列 IN() GROUP BY HAVING COUNT DISTINCT
【发布时间】:2017-11-15 10:12:07
【问题描述】:

具有以下型号:

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"

要获取包含 所有 TAGLIST 中给出的 tagid 的帖子的 postid,其中 TAGLEN 是 TAGLIST 中的 tagid 数:

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

但是我如何使用 Django ORM 做到这一点?

【问题讨论】:

  • 为什么你不使用外键,顺便说一句 this 帖子对 taginput 有好处:)
  • posttag.objects.get(tagid__icontains=you_list).postid 这将返回包含列表中标签的帖子标签的帖子 ID
  • @mohammedqudah:但它应该包含所有标签。
  • @mohammedqudah 我考虑过使用外键,但我决定不这样做,因为可能有多少。
  • 别忘了阅读 tagsinput :)

标签: django group-by distinct django-orm having


【解决方案1】:

我找到了解决办法。

    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)

在所有这些上运行 .query.__str__() 基本上会返回以下 SQL。

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

【讨论】:

  • 推荐任何改进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多