views:

198

answers:

1

Hi,

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)
+2  A: 

It should be:

foundContacts.order_by("classification__kam")

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

You can also see some examples in the order_by reference:
http://docs.djangoproject.com/en/1.1/ref/models/querysets/#order-by-fields

Mark Lavin
The syntax is correct, but this has nothing to do with view vs template. You can't do this sort of ordering in the template at all (because template syntax doesn't allow you to call functions with arguments). But the double-underscore syntax is used for all relationship traversals *within* a function call - filter, annotate, order_by, etc. Whereas the normal dot syntax is for when you have an object and want to refer to the related object.
Daniel Roseman
The wording was poor and I have removed it.
Mark Lavin
Ok it works now. Thanks!
Tom Tom