Reputation: 967
I would like to ask assistance with this matter, I am trying to order the queryset of Job_Posting
through .order_by('fkey')
but I would like to order it alphabetically not by foreign key
class Job(models.Model):
Job_Position = models.CharField(max_length=30, null=True)
Num_Positions = models.CharField(max_length=30, null=True)
def __unicode__(self):
return self.Job_Position
class Job_Posting(models.Model):
fkey = models.ForeignKey("Job")
Job_Description = models.TextField(max_length=500, null=True)
Via
job_list = Job_Posting.objects.all().order_by('fkey')
Expected results
My current results with .order_by('fkey')
Is it possible to list them alphabetically through .order_by()
or there some other way to do this? Thanks in advance.
Upvotes: 0
Views: 121
Reputation: 811
job_list = Job_Posting.objects.order_by('fkey__Job_Position')
From the documentation:
To order by a field in a different model, use the same syntax as when you are querying across model relations. That is, the name of the field, followed by a double underscore (__), followed by the name of the field in the new model, and so on for as many models as you want to join.
Upvotes: 1
Reputation: 9110
Job_Posting.objects.order_by("fkey__Num_Positions")
or
Job_Posting.objects.order_by("fkey__Job_Position")
depending on which field from Job
model you want to order by.
Upvotes: 2
Reputation: 43300
As noted in the docs, when you order by a foreign key it is ordered by the id of that key (by default). Since you want to order by a field on that fk then you need to use __
to denote the field name also
job_list = Job_Posting.objects..order_by('fkey__Job_Position')
Note: The .all()
was also not needed.
Upvotes: 2