django queryset: how to order by a (backwards) related field?
In this situation I have two models, Comment and Score. The relationship is defined in the Score model, like so:
class Comment(models.Model):
content = TextField()
...
class Score(models.Model):
comment = models.ForeignKey(Comment)
value = models.IntegerField()
My question i开发者_高级运维s: How do I construct a queryset that returns all Comments and is ordered by the value of Score?
Thanks in advance!
Martin
You should change your Score model to use a OneToOne field, not a ForeignKey - an FK implies there is more than one Score per Comment, which would never work.
However either way, the query can be done like this:
Comment.objects.order_by('score__value')
I'm still new to Django, but been working w/ it for a couple months now. I think this snippet might work (in ascending order, for descending use '-value'
):
comments = [ score.comment for score in Score.objects.order_by('value').all() ]
精彩评论