开发者

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() ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜