Queryset API distinct() does not work?

后端 未结 2 1748
执念已碎
执念已碎 2021-01-05 12:52
class Message(models.Model):
    subject = models.CharField(max_length=100)
    pub_date = models.DateTimeField(default=datetime.now())

class Topic(models.Model):
          


        
2条回答
  •  耶瑟儿~
    2021-01-05 13:49

    You don't need distinct() here, what you need is aggregation. This query will do what you want:

    from django.db.models import Max
    Topic.objects.annotate(Max('message__pub_date')).order_by('-message__pub_date__max')
    

    Though if this is production code, you'll probably want to follow akaihola's advice and denormalize "last_message_posted" onto the Topic model directly.

    Also, there's an error in your default value for Message.pub_date. As you have it now, whenever you first run the server and this code is loaded, datetime.now() will be executed once and that value will be used as the pub_date for all Messages. Use this instead to pass the callable itself so it isn't called until each Message is created:

    pub_date = models.DateTimeField(default=datetime.now)
    

提交回复
热议问题