Juan Carlos Asuncion
Juan Carlos Asuncion

Reputation: 967

ordering by a field in a foreign key alphabetically

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

Answers (3)

sean
sean

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

doru
doru

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

Sayse
Sayse

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

Related Questions