django-orm django-orm 使链接查询(LEFT JOIN)的条件 写在 ON 之后,而不是 WHERE

直接上代码:

注:FilteredRelation 不能使用嵌套查询。

from django.db.models import Q,FilteredRelation

class Books(Model):
    id = ...
    book_name = ...
    author = models.ForeignKey('apps.Author')

class Author(Model):
    id = ...
    author_name = ...
    sex = ...


Author.objects.annotate(b = FilteredRelation("books", condition=Q(books__book_name = "盗墓笔记"))).filter(id = 10)
SELECT 
    * 
FROM 
    author 
    LEFT JOIN books b ON b.`author` = author.id AND b.book_name = "盗墓笔记"
WHERE 
    author.id = 10
posted @ 2021-04-01 10:19  做个笔记  阅读(1657)  评论(0编辑  收藏  举报