class Message(models.Model): subject = models.CharField(max_length=100) pub_date = models.DateTimeField(default=datetime.now()) class Topic(models.Model): title = models.CharField(max_length=100) message = models.ManyToManyField(Message, verbose_name='Discussion')
I want to get order all the topics according to the latest message object attached to that topic. I executed this query but this does not give the distinct queryset.
>> Topic.objects.order_by('-message__pub_date').distinct()
You’ll find the explanation in the documentation for
.distinct().I would de-normalize by adding a
modified_datefield to theTopicmodel and updating it whenever a Message is saved or deleted.