[Django]-Django order by related field

49๐Ÿ‘

โœ…

It should be:

foundContacts.order_by("classification__kam")

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

You can also see some examples in the order_by reference:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by

๐Ÿ‘คMark Lavin

0๐Ÿ‘

as the documentation indicates, it should be used as in queries about related models

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#order-by

foundContacts.order_by("classification__kam")

0๐Ÿ‘

Iโ€™ve struggled a lot with this problem, this is how I solved it:

  1. contact ordered by "kam" (Classification) field:
show_all_contact = Contact.objects.all().order_by(title__kam)
  1. classification ordered by Users email (no sense in it, but only show how it works):
show_all_clasification = Classification.objects.all().order_by(kam__email)
๐Ÿ‘คoruchkin

Leave a comment