Django ORM 多表联查问题
有两张模型,专题和文章,一对多的关系,如何使用Django ORM找到存在文章的专题列表?
class Subject(models.Model): """专题"""
id = models.CharField(default=str(uuid4()).replace('-', ''), primary_key=True, max_length=32)
title = models.CharField(max_length=64)
class Meta:
db_table = 'subjects'
class Article(models.Model):
"""文章"""
id = models.CharField(default=str(uuid4()).replace('-', ''), primary_key=True, max_length=32)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
class Meta:
db_table = 'articles'
- 我想要的结果用原生SQL是这样的:
SELECT s.id sub_id, s.title sub_title, count(a.id) art_countFROM subjects AS s
JOIN articles AS a ON s.id = a.subject_id
GROUP BY s.id
HAVING art_count > 0
ORDER BY art_count
以上是 Django ORM 多表联查问题 的全部内容, 来源链接: utcz.com/p/937918.html