views:

111

answers:

2

Hi folks!

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 is: How do I construct a queryset that returns all Comments and is ordered by the value of Score?

Thanks in advance!

Martin

+1  A: 

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() ]
kchau
+4  A: 

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')
Daniel Roseman