Django order by related field

Viewed 26424

I want to sort a QuerySet of contacts by a related field. But I do not know how. I tried it like this, but it does not work.

foundContacts.order_by("classification.kam")

Actually in a template I can access the kam value of a contact through contact.classification.kam since it is a OneToOne relationship.

The (simplified) models look like this:

class Classification(models.Model):
    kam = models.ForeignKey(User)
    contact = models.OneToOneField(Contact)

class Contact(models.Model):
    title = models.ForeignKey(Title, blank=True, null=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
3 Answers

I've struggled a lot with this problem, this is how I solved it:

  1. contact ordered by "kam" (Classification) field:
show_all_contact = Contact.objects.all().order_by(title__kam)
  1. classification ordered by Users email (no sense in it, but only show how it works):
show_all_clasification = Classification.objects.all().order_by(kam__email)
Related