0

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

是否可以通过相当于 SQL 的 Django ORM 进行一次查询:

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
4

1 回答 1

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

使用inorder_byqueryset 方法,反向查询关系,并切片以限制结果

于 2013-11-07T13:56:19.277 回答