Translating query with JOIN expressions and a generic relation to Django ORM

早过忘川 提交于 2019-12-07 02:48:28

After another day of struggling, I've finally solved it. Although it does not produce the same query from above and is not efficient like it (because it's selecting all likes on the queried event), it seems like it's the only good way of doing it in ORM:

from django.db.models import Case, When, F

Event.objects.filter( \
        Q(business__manager=person) | \
        Q(likes__person=person)) \
    .order_by( \
        Case( \
            When(likes__person=person, then=F('likes__date')), \
            default=F('when')) \
    .desc())

Here's what SQL it produces:

SELECT event.*
FROM event
INNER JOIN
    business
    ON (event.business_id = business.id)
LEFT OUTER JOIN
    'like'
    ON (event.id = object_id AND content_type_id = 17)
WHERE (business.manager_id = 2 OR 'like'.person_id = 2)
ORDER BY CASE
    WHEN 'like'.person_id = 2 THEN 'like'.date
    ELSE event.'when'
END DESC;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!