Issue
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)
Solution
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:
https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.order_by
Answered By - Mark Lavin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.