[Django]-Django Generic Foreign Key Sorting

5๐Ÿ‘

โœ…

If you want them treated the same way (deducing this from the fact that you want them sorted by their common name field) then this indicates that these models have the same base.

Use model inheritance in that case with a base model that is abstract and defines the name field and the generic fkey relation.

class RequestBase(models.Model):
    name = models.CharField(max_length=50, db_index=True)
    statuses = GenericRelation(Status, related_query_name='request')

    class Meta:
        abstract = True

class Request(RequestBase):
    # ... more fields

Status.objects.all().order_by('request__name')

A more general explanation: to be able to sort objects by one attribute, you have to make clear that they all share that same attribute. Either by fetching the values in your own routines and creating lists that are sortable (this would be the qs approach you mentioned) or by creating a common interface โ€“ which is this Model inheritance approach.

As long as you are not using table inheritance, though, you will not be able to use the database for sorting (meaning: you cannot use the Django ORM for sorting).

There are certainly other approaches, including those that are outside of Django models: for example generating an additional lookup structure like a search index which will contain your transformed data as required (e.g. a haystack index).

๐Ÿ‘คRisadinha

Leave a comment