考慮這兩款車型:通過反向排序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)
請使用''CamelCase''在Python中,例如類名''PMThread''和''PMMessage''。 – niekas