Django Order_by Foreignkey Set Models
I have following django models class Post(models.Model): title = models.CharField(max_length=240) class Comment(models.Model): post = models.ForeignKey(Post) date = mo
Solution 1:
You may not use methods in order_by lookups because they are converted to SQL.
So, why not convert get_last_comment_date into a field ? e.g. using a signal receiver:
from django.db.models import signals
classPost(models.Model):
title = models.CharField(max_length=240)
last_comment_date = models.DateField(null=True, blank=True)
defpost_last_comment_date(sender, instance=None, **kwargs):
try:
last_comment_date = self.comment_set.order_by('-date')[0].date
except Comment.DoesNotExist:
returnif last_comment_date != comment.post.last_comment_date:
comment.post.last_comment_date = last_comment_date
comment.post.save()
signals.post_save.connect(post_last_comment_date, sender=Comment)
Now, you can: Comment.objects.order_by('post__last_comment_date', '-date')
Post a Comment for "Django Order_by Foreignkey Set Models"