class Business(models.Model):
manager = models.ForeignKey(User, on_delete=models.CASCADE)
#...
class Event(models.Model):
business = models.ForeignKey(Business, on_delete=models.CASCADE)
text = models.TextField()
when = models.DateTimeField()
likes = GenericRelation('Like')
class Like(models.Model):
person = models.ForeignKey(User, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
date = models.DateTimeField(auto_now=True)
所以我在models.py
中有这个结构。以下是重要模型的解释:
事件模型具有链接到特定Business对象的“business”字段,其还具有“manager”字段。此外,事件模型具有“when”字段,该字段描述事件发生的日期
另一方面,Like模型具有可以链接到特定Event对象的通用外键字段,以及描述谁给予喜欢以及何时给予该事件的“人”和“日期”字段。
现在的目标是在用户页面上显示目标用户所有喜欢的事件,以及管理员是该用户的所有事件。可以使用此SQL命令完成它:
SELECT event.*
FROM event
INNER JOIN
business
ON (event.business_id = business.id)
LEFT JOIN
'like'
ON (event.id = object_id AND content_type_id = 17)
WHERE ('like'.person_id = 1 OR business.manager_id = 1);
但是现在必须对结果进行排序,已经提到了Like中的“date”和Event模型中的“when”。排序行为应如下所示:如果Event对象派生自Like对象,那么它应该在Like对象中按“date”排序,在其他情况下,它应该按Event中的“when”排序 - 这是事情发生变化的地方。因此,这是最终原始查询的样子:
SELECT event.*
FROM event
INNER JOIN
business
ON (event.business_id = business.id AND business.manager_id = 1)
LEFT JOIN
'like'
ON (event.id = object_id AND content_type_id = 17 AND person_id = 1)
ORDER BY COALESCE('like'.date, event.'when') DESC;
我现在要把最后一个查询翻译成Django ORM,但我完全迷失了。谁能帮我?提前谢谢!
答案 0 :(得分:0)
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())
这是它产生的SQL:
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;