codyc4321
codyc4321

Reputation: 9682

determine a model's default order by a field of its foreign key Django

I want to order a model based on a field of its foreign key. I find results when googling this as to the ORM, but I'm before that, declaring the metaclass. They show things such as

 units = Unit.objecwhere to lookts.filter(color='red').order_by('location__label')

but I want to order on declaration automatically:

class Office(models.Model):
    objects = OfficeManager()
    id = models.IntegerField(db_column='office_id', primary_key=True)
    office = models.CharField(max_length=20)
    description = models.CharField(max_length=255)

    class Meta:
        db_table = 'tblOffices'
        ordering = ('office',)

    def __str__(self):
        return self.office


class OfficeCity(models.Model):
    office = models.ForeignKey(Office, db_column='tblOffices')
    name = models.CharField(max_length=255)

    class Meta:
        db_table = 'cities'
        ordering = ('office.description')

Is the above code snippet correct to order these cities by the FK description field? Thank you

Attached is a demo of a django learner's "googling it in less than or equal to 15 seconds", end quote.

enter image description here

enter image description here

Note that in the second picture, the django learner may be tempted to click on https://docs.djangoproject.com/en/1.9/ref/models/fields/ and read the entire 26 pages (from if you were to print it), spending a few hours relearning useful things they've already read, but surely not finding an answer to the question by "googling it within 15 seconds". This leads one to believe that possibly the person who googled it within 15 seconds already knew where to look and what to look for, which is why it took them 15 seconds, but for the learner it would take several hours to find the answer. If the learner is not implementing this feature, but merely curious, it would seem a Q&A forum is the proper place to seek answers (the A part of Q&A) by positing questions (the Q part). Let's leave the ego to the brain surgeons guys, we understand if you've been doing this for 30 years you're an expert, those of us half your age learning this will be an expert when we're 60 too. Hopefully we remain humble, however...

Upvotes: 0

Views: 515

Answers (1)

François Constant
François Constant

Reputation: 5496

class Meta:
    ordering = ('office__description',)

Upvotes: 2

Related Questions