Question

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

Was it helpful?

Solution

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

OTHER TIPS

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() ]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top