2014-01-05 56 views
1

考慮這兩款車型:通過反向排序ForeignKey DateTimeField?

class pm_thread(models.Model): 
    subject = models.CharField(max_length=200) 
    participants = models.ManyToManyField(User) 

    def latest_message(self): 
     message = self.message_set.order_by('-datetime') 
     if message: 
      return message[0] 
     return None 

class pm_message(models.Model): 
    thread = models.ForeignKey(pm_thread, related_name='message_set') 
    user = models.ForeignKey(User, related_name='sent_message') 
    datetime = models.DateTimeField(auto_now_add=True) 
    content = models.TextField() 

我怎麼能爲了一個pm_thread查找的最新消息的日期?例如:

threads = pm_thread.objects.filter(participants=request.user).order_by(latest_message.datetime) 
+2

請使用''CamelCase''在Python中,例如類名''PMThread''和''PMMessage''。 – niekas

回答

3

嘗試:

threads = pm_thread.objects.filter(participants=request.user).order_by('-pm_message__datetime') 
+0

該查詢返回每個pm_message的dublicate線程記錄。你如何將''distinct()''應用於這個查詢? – niekas

+0

@niekas:重複是數據庫的問題。在存儲數據時應該小心, –

+0

您可以使用不同的djangos:https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct – lev