Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django order by related field

Tags:

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)
like image 842
Thomas Kremmel Avatar asked Jan 14 '10 16:01

Thomas Kremmel


2 Answers

It should be:

foundContacts.order_by("classification__kam")

Here is a link for the Django docs on making queries that span relationships: https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

You can also see some examples in the order_by reference:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by

like image 154
Mark Lavin Avatar answered Oct 10 '22 04:10

Mark Lavin


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)
like image 43
oruchkin Avatar answered Oct 10 '22 05:10

oruchkin