通过在django orm中使用多对多关系来执行组?

iswrvxsc  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(347)

我有以下型号:

  1. class Tag(models.Model):
  2. name = models.CharField(max_length=255, unique=True, default="")
  3. class Problem(models.Model):
  4. tags = models.ManyToManyField(Tag, related_name="problems")
  5. index = models.CharField(max_length=5)
  6. name = models.CharField(max_length=255)
  7. rating = models.IntegerField(default=-1)

我要执行以下查询:

  1. SELECT
  2. "p"."index",
  3. "p"."name",
  4. "p"."rating"
  5. FROM
  6. problem p
  7. WHERE
  8. p.id IN (
  9. SELECT
  10. pt.problem_id
  11. FROM
  12. problem_tags pt
  13. JOIN tag t ON pt.tag_id = t.id
  14. WHERE
  15. t.name IN ('math', 'binary search', 'implementation')
  16. GROUP BY
  17. pt.problem_id
  18. HAVING
  19. COUNT(*) = 3
  20. )
  21. ORDER BY
  22. rating,
  23. index;

我用了这样的方法:

  1. Problem.tags.through.objects.values("problem_id").filter(
  2. tag__name__in=("math", "binary search", "implementation")
  3. ).annotate(count=models.Count("*")).filter(count=3)

但它发出以下查询 COUNT(*)SELECT 是多余和错误的:

  1. SELECT
  2. "api_problem_tags"."problem_id",
  3. COUNT(*) AS "count"
  4. FROM
  5. "api_problem_tags"
  6. INNER JOIN "api_tag" ON ("api_problem_tags"."tag_id" = "api_tag"."id")
  7. WHERE
  8. "api_tag"."name" IN ('math', 'binary search', 'implementation')
  9. GROUP BY
  10. "api_problem_tags"."problem_id"
  11. HAVING
  12. COUNT(*) = 3

我怎样才能摆脱第一个 COUNT(*)

rdrgkggo

rdrgkggo1#

我想你可以用 Count 以及 filter 参数。

  1. Problem.objects.annotate(
  2. tag_count=Count(
  3. 'tags',
  4. filter=Q(tags__name__in=["math", "binary search", "implementation"],
  5. )
  6. ).filter(tag_count=3)

相关问题