如何使用Django ORM进行查询?

时间:2013-11-07 13:49:48

标签: django django-models django-orm

我有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

1 个答案:

答案 0 :(得分:1)

messages = Message.objects.filter(thread__id__in=[1,2,3]).order_by('date')[:10]

使用inorder_by查询集方法,querying across a relationship in reverseslicing to limit the results