我有2个django模型:
class Message(models.Model):
msg = models.CharField(max_length=200)
date = models.DateTimeField(auto_now_add=True)
class Thread(models.Model):
messages = models.ManyToManyField(Message)
是否可以通过Django ORM进行一次查询,相当于SQL:
SELECT Message.msg, Message.date
FROM Message, Thread
WHERE Message.id IN Thread.messages
AND Thread.id IN (1,2,3)
ORDER BY Message.date
LIMIT 10
答案 0 :(得分:1)
messages = Message.objects.filter(thread__id__in=[1,2,3]).order_by('date')[:10]
使用in
和order_by
查询集方法,querying across a relationship in reverse和slicing to limit the results